Last active
March 14, 2018 23:51
-
-
Save MaxGraey/49f81ff07dd9467f48e05977110a7010 to your computer and use it in GitHub Desktop.
Fast RFC-compliant UUID v4 Generator
This file contains hidden or 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
const charset = '0123456789abcdef'.split(''); | |
const randomset = new Uint8Array(16); | |
export function uuid() { | |
let rand = 0; | |
for (let i = 0; i < 16; i++) { | |
if (rand < 2) { | |
rand += Math.random() * (1 << 24); | |
} | |
randomset[i] = rand & 0xFF; | |
rand >>>= 8; | |
} | |
randomset[6] = (randomset[6] & 0x0F) | 0x40; | |
randomset[8] = (randomset[8] & 0x3F) | 0x80; | |
let output = ''; | |
for (let i = 0; i < 16; i++) { | |
const rnd = randomset[i]; | |
output += charset[rnd & 15]; | |
output += charset[rnd >>> 4]; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another version with one uniform loop (slightly slower):