Skip to content

Instantly share code, notes, and snippets.

@MaxGraey
Last active March 14, 2018 23:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxGraey/49f81ff07dd9467f48e05977110a7010 to your computer and use it in GitHub Desktop.
Save MaxGraey/49f81ff07dd9467f48e05977110a7010 to your computer and use it in GitHub Desktop.
Fast RFC-compliant UUID v4 Generator
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;
}
@MaxGraey
Copy link
Author

MaxGraey commented Mar 14, 2018

Another version with one uniform loop (slightly slower):

export function uuid() {
  let rand = 0;
  let output = '';
  for (let i = 0; i < 16; i++) {
    if (rand < 2) {
      rand += Math.random() * (1 << 24);
    }

    switch (i) {
      case 6: rand = (rand & 0x0F) | 0x40; break;
      case 8: rand = (rand & 0x3F) | 0x80; break;
      // forcing compiler build optimal jump table for us
      case 0: case 1: case 2:
      case 3: case 4: case 5:
      default: rand &= 0xFF; break;
    }

    output += charset[rand & 15];
    output += charset[rand >>> 4];

    rand >>>= 8;
  }

  return output;
}

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