Skip to content

Instantly share code, notes, and snippets.

@duzun
Last active February 27, 2024 18:31
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save duzun/d1bfb5406a362e06eccd to your computer and use it in GitHub Desktop.
Save duzun/d1bfb5406a362e06eccd 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('-');
}
@jorisw
Copy link

jorisw commented Feb 26, 2024

Would suggest renaming s() and h() to better describe their role in the function as a whole.

Also, the n param could be named length.

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