Skip to content

Instantly share code, notes, and snippets.

@tyler-johnson
Created February 6, 2015 00:53
Show Gist options
  • Save tyler-johnson/c98cc17c8ce16ae22046 to your computer and use it in GitHub Desktop.
Save tyler-johnson/c98cc17c8ce16ae22046 to your computer and use it in GitHub Desktop.
a random ID generator with variable length and content
var crypto = require("crypto");
var RAND_ALPHA_NUMERIC = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
module.exports = function randId(n, list) {
var id, rand_nums, i, len;
if (n == null) n = 8;
if (list == null) list = RAND_ALPHA_NUMERIC;
id = "";
rand_nums = crypto.randomBytes(n);
len = rand_nums.length;
for (i = 0; i < len; i++) {
id += list[Math.floor((rand_nums.readUInt8(i) / 256) * list.length)];
}
return id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment