Thursday, October 25, 2007

Javascript Random Text

Following javascript is to create some mock contacts for UI testing purpose:
    function createMockContacts(contactNumber) {
        var contacts = new Array();
        for (var i = 0; i < contactNumber; i++) {
            var contact = new Object();
            contact.Name = randomText(8);
            contact.Company = randomText(16);
            contact.Phone = randomText(9, "phone");
            contact.Email = randomText(9, "email");
            contact.Address = randomText(20);
            contacts.push(contact);
        }
        return contacts;
    }
    function randomText(length, type) {
        if ( type == "phone") 
            var chars = "1234567890";
        else 
            var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var text = "";
        for (var i = 0; i < length; i++) {
            text += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        if (type == "email" && text.length > 3)
            text = text.slice(0, 3) + "@" + text.slice(3) + ".com";

        return text;
    }
Return is an array of javascript objects:
 contacts[0].Name = "7k15zlQQ"
 contacts[0].Company = "sTOX2EVFhsBXJFIn"
 contacts[0].Phone = "881414055"
 contacts[0].Email = "3Ic@Adu2N3.com"
 contacts[0].Address = "lN3kSwJCJC3m7gC8zdZy" 
 contacts[1].Name = "IZYkS3gI"
 ...