Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active November 22, 2016 07:05
Show Gist options
  • Save davidgilbertson/4ce2cc7e1deb809ea6f7 to your computer and use it in GitHub Desktop.
Save davidgilbertson/4ce2cc7e1deb809ea6f7 to your computer and use it in GitHub Desktop.
var ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
random_base64 = function random_base64(length) {
var str = "";
for (var i=0; i < length; ++i) {
var rand = Math.floor(Math.random() * ALPHABET.length);
str += ALPHABET.substring(rand, rand+1);
}
return str;
}
var stringLength = 5; // because I don't have all day
var i;
var nums = [];
var safety = 100000;
console.log('Generating random strings with', Math.pow(ALPHABET.length, stringLength).toLocaleString(), 'combinations');
for (i = 0; i < safety; i++) {
var num = random_base64(stringLength);
if (nums.indexOf(num) > -1) {
console.log(num, 'was generated twice after', i.toLocaleString(), 'tries');
break;
}
nums.push(num);
}
@davidgilbertson
Copy link
Author

Run this in your console (or Chrome Dev Tools snippet). You'll get something interesting like this:

Generating random strings with 1,073,741,824 combinations
sH1Ru was generated twice after 43,132 tries

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment