Skip to content

Instantly share code, notes, and snippets.

@jhsuZerion
Created February 22, 2018 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhsuZerion/3d0f586a55a9a1ddadef4ef96b6b4fbd to your computer and use it in GitHub Desktop.
Save jhsuZerion/3d0f586a55a9a1ddadef4ef96b6b4fbd to your computer and use it in GitHub Desktop.
Function to generate a set of unique alphanumeric codes with a prefixed timestamp
/**
* Generate a set of unique alphanumeric codes with a timestamped prefix
* prefix is parsed as an octal value
* remainder of the code is in the pattern A99, first character is a letter followed by two numbers
* every three characters are separated by a hyphen
* @param {int} num_codes the number of codes to generate
* @param {int} code_length the length of codes, does not include hyphens
* @return {array} list of codes
*/
function simpleCodeGenerator(num_codes,code_length) {
if(num_codes > 500) num_codes = 500;
if(code_length < 4) code_length = 4;
if(code_length > 16) code_length = 16;
if(num_codes > Math.pow(10,code_length)) return [];
var codes = [];
var code = "";
var digits = "0123456789";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var d = new Date();
var prefix = Number(String(d.getFullYear().toString().substr(2, 4)) + String(d.getMonth() + 1) + String(d.getDate())).toString(16);
var prefix_len = prefix.length;
// if random
for (var x = 0; x < num_codes; x++) {
do {
code = prefix;
for (var i = 0; i < code_length-prefix_len; i++) {
if (i % 3 === 0) code += "-";
if (i % 3 === 0 && (code_length-prefix_len) > i+2) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
} else {
code += digits.charAt(Math.floor(Math.random() * digits.length));
}
}
} while (codes.indexOf(code) >= 0);
codes.push(code);
}
return codes;
}
// console.log(simpleHexCodes(100,5));
// var test = (3245).toString(2).match(/1/g).length;
// var test = ("a,b,c,d,e,f,g").split(", ").length;
console.log(simpleCodeGenerator(8,8));
// console.log((3245).toString(2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment