Skip to content

Instantly share code, notes, and snippets.

@kamronbatman
Created April 27, 2018 01:53
Show Gist options
  • Save kamronbatman/a48b6bcb2d66e933f1109755e429bed1 to your computer and use it in GitHub Desktop.
Save kamronbatman/a48b6bcb2d66e933f1109755e429bed1 to your computer and use it in GitHub Desktop.
Modern UUIDv4 for Browsers using ES6
const hex = bytes => bytes.reduce((total, byte) => (
total + byte.toString(16).padStart(2, '0')
), '');
const genUUID = () => {
const bytes = new Uint8Array(16);
window.crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const p1 = hex(bytes.subarray(0, 4));
const p2 = hex(bytes.subarray(4, 6));
const p3 = hex(bytes.subarray(6, 8));
const p4 = hex(bytes.subarray(8, 10));
const p5 = hex(bytes.subarray(10, 16));
return `${p1}-${p2}-${p3}-${p4}-${p5}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment