Skip to content

Instantly share code, notes, and snippets.

@SCG82
Created March 27, 2022 12:34
Show Gist options
  • Save SCG82/391543db918b4ea1a20a828f69e8dc1f to your computer and use it in GitHub Desktop.
Save SCG82/391543db918b4ea1a20a828f69e8dc1f to your computer and use it in GitHub Desktop.
Generate a 36-character (128-bit) Universally Unique IDentifier (v4)
/**
* Generate a 36-character (128 bit) Universally Unique IDentifier (v4)
* @param {Number} length [Optional] length of the output string (default = 36)
* @param {String} str [Optional] string to start with
*/
function UUID(length = 36, str = '') {
let a = 36 - length + str.length
while (a++ < 36) {
str +=
(a * 51) & 52
? (a ^ 15
? 8 ^ (Math.random() * (a ^ 20 ? 16 : 4))
: 4
).toString(16)
: '-'
}
return str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment