Skip to content

Instantly share code, notes, and snippets.

@richsilv
Last active August 29, 2015 14:18
Show Gist options
  • Save richsilv/645e69e24f3a03520765 to your computer and use it in GitHub Desktop.
Save richsilv/645e69e24f3a03520765 to your computer and use it in GitHub Desktop.
Random code generator (numbers and letters) of prescribed format (e.g. Postcode, NI number)
var randomLetter = function() {return String.fromCharCode(Math.floor(Math.random()*26) + 65);}
var randomNumber = function() {return String.fromCharCode(Math.floor(Math.random()*10) + 48);};
var genDict = {
'l': randomLetter,
'n': randomNumber
};
// pass in a format string of the type: "4l 3n 2l", i.e. a space-delimited set of number/letter
// pairs, the first of which gives the number of characters of the given type and the second
// denotes the type: "n" for number, "l" for letter (always upper-case).
// As an example, "2l 3n 2l" would give a realistic, space-free UK postcode.
var randomCode = function(format) {
var code = '';
format.split(' ').forEach(function(token) {
var type = token.substr(token.length - 1).toLowerCase(),
generator = genDict[type],
repeats = parseInt(token.substr(0, token.length - 1), 10),
i;
if (!genDict) return null;
for (i = 0; i < repeats; i++) code += generator();
});
return code;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment