Skip to content

Instantly share code, notes, and snippets.

@webolizzer
Last active January 3, 2018 14:19
Show Gist options
  • Save webolizzer/e521db1b1401080b98f06c46c837be6f to your computer and use it in GitHub Desktop.
Save webolizzer/e521db1b1401080b98f06c46c837be6f to your computer and use it in GitHub Desktop.
ES6 random guid generator
var t0 = performance.now();
//
// @source https://gist.github.com/webolizzer/e521db1b1401080b98f06c46c837be6f
//
function get_random_guid() {
const POSSIBILITIES_PER_ROUND = 512;
const UUID_TMPL = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
let Chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let get_random_char = () => {
// we create first a large empty array for random chars
let PossibilitiesArray = [...Array(POSSIBILITIES_PER_ROUND).keys()];
// @then we fill this array with random chars
// @note every aray value is random!
let MapCb = () => {
let CharsArray = Chars.split('');
let RandomChar = CharsArray[Math.floor(Math.random() * CharsArray.length)];
return RandomChar;
};
let RandomCharsArray = PossibilitiesArray.map(MapCb);
// @then we get a random char from RandomCharsArray
let RandomChar = RandomCharsArray[Math.floor(Math.random() * RandomCharsArray.length)];
return RandomChar;
};
// @then we replace characters of UUID_TMPL with random chars
// @note every single replacement will call get_random_char()
return UUID_TMPL.replace(/[x]/g, () => get_random_char());
}
console.log(get_random_guid());
//
var t1 = performance.now();
console.log("Call took " + (t1 - t0) + " milliseconds.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment