Skip to content

Instantly share code, notes, and snippets.

@shamasis
Last active August 29, 2015 14:13
Show Gist options
  • Save shamasis/dae827ad76431936a572 to your computer and use it in GitHub Desktop.
Save shamasis/dae827ad76431936a572 to your computer and use it in GitHub Desktop.
UUID (GUID) generation
/**
* Returns unique GUID on every call as per pseudo-number RFC4122 standards.
*
* @type {function}
* @returns {string}
*/
module.exports = (function() {
var E = '',
H = '-',
rnd = (window || global).Math.random;
return function() {
var n, r; // r = result , n = numeric variable for positional checks
// if "n" is not 9 or 14 or 19 or 24 return a random number or 4
// if "n" is not 15 genetate a random number from 0 to 15
// `(n ^ 20 ? 16 : 4)` := unless "n" is 20, in which case a random number from 8 to 11 otherwise 4
//
// in other cases (if "n" is 9,14,19,24) insert "-"
for (r = n = E; n++ < 36; r += n * 51 & 52 ? (n ^ 15 ? 8 ^ rnd() * (n ^ 20 ? 16 : 4) : 4).toString(16) : H);
return r;
}
}());
/**
* Returns unique GUID on every call as per pseudo-number RFC4122 standards.
*
* @type {function}
* @returns {string}
*
* @note Uses string replacement to build the ID.
*/
module.exports = (function() {
var MASK = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx',
SX = 'x',
base = 16,
rnd = Math.random,
flr = Math.floor,
now = Date.now;
return function() {
var d = now();
return (MASK.replace(/[xy]/g, function(c) {
var r = (d + rnd() * base) % base | 0;
d = flr(d / base);
return (c === SX ? r : (r & 0x7 | 0x8)).toString(base);
}));
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment