Created
November 3, 2012 20:31
-
-
Save renatoathaydes/4008624 to your computer and use it in GitHub Desktop.
Util JavaScript functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
var chars = "abcdefghijklmnopqrstuvxzwyABCDEFGHIJKLMNOPQRSTUVXZWY0123456789~`!@#$%^&*()-_=+{[}]|\\;:'\"<,>.?/"; | |
/** | |
* Get a random char according to the optionsl options given. | |
* @param options can be one of: | |
* <ul> | |
* <li><b>'alpha'</b>: only returns alphabetic chars</li> | |
* <li><b>'lowercase'</b>: only returns alphabetic chars</li> | |
* <li><b>'uppercase'</b>: only returns alphabetic chars</li> | |
* <li><b>'any'</b>: returns alpha-numeric chars and some symbols</li> | |
* </ul> | |
* @returns char | |
*/ | |
function randomChar(options) { | |
switch(options) { | |
case 'alpha': return chars.slice(0, 52)[randomInt(chars.length)]; | |
case 'lowercase': return chars.slice(0, 26)[randomInt(chars.length)]; | |
case 'uppercase': return chars.slice(27, 52)[randomInt(chars.length)]; | |
case 'any': default: return chars[randomInt(chars.length)]; | |
} | |
} | |
/** | |
* @param n default is 100. | |
* @returns int between 0 and n. | |
*/ | |
function randomInt(n) { | |
return Math.floor(Math.random() * (n || 100)); | |
} | |
/** | |
* @param obj to check | |
* @returns number of fields in the object | |
*/ | |
function fieldCount(obj) { | |
var count = 0; | |
for (var a in obj) { | |
count += 1; | |
} | |
return count; | |
} | |
// expose Util to the global scope. | |
Util = { | |
chars: chars, | |
randomInt: randomInt, | |
randomChar: randomChar, | |
fieldCount: fieldCount | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment