Skip to content

Instantly share code, notes, and snippets.

@ukchukx
Forked from duzun/uuid.js
Created January 17, 2018 22:41
Show Gist options
  • Save ukchukx/6178a2ccd2ff10b23a5995cf6b11bbdc to your computer and use it in GitHub Desktop.
Save ukchukx/6178a2ccd2ff10b23a5995cf6b11bbdc to your computer and use it in GitHub Desktop.
A simple UUID v4 generator, relying on Math.random() + Date.now()
/** Generates UUID v4
*
* @node There is a bug in Chrome's Math.random() according to http://devoluk.com/google-chrome-math-random-issue.html
* For that reason we use Date.now() as well.
*/
function UUID() {
function s(n) { return h((Math.random() * (1<<(n<<2)))^Date.now()).slice(-n); }
function h(n) { return (n|0).toString(16); }
return [
s(4) + s(4), s(4),
'4' + s(3), // UUID version 4
h(8|(Math.random()*4)) + s(3), // {8|9|A|B}xxx
// s(4) + s(4) + s(4),
Date.now().toString(16).slice(-10) + s(2) // Use timestamp to avoid collisions
].join('-');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment