Skip to content

Instantly share code, notes, and snippets.

@Aaron-P
Created July 5, 2021 01:27
Show Gist options
  • Select an option

  • Save Aaron-P/3ddbe9aa7d85807d94e19a6000dd1f58 to your computer and use it in GitHub Desktop.

Select an option

Save Aaron-P/3ddbe9aa7d85807d94e19a6000dd1f58 to your computer and use it in GitHub Desktop.
JavaScript UUID v4 generation
function UUIDv4() {
const bytes = new Uint8Array(16);
window.crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
// Is there a better way of getting our string from the byte array?
const hex = bytes.reduce((output, byte) => (output + ("0" + byte.toString(16)).slice(-2)), "");
return `${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20, 32)}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment