-
-
Save ukchukx/6178a2ccd2ff10b23a5995cf6b11bbdc to your computer and use it in GitHub Desktop.
A simple UUID v4 generator, relying on Math.random() + Date.now()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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