Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active August 16, 2022 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/3f0e90aee377635a3dedaa4c7b07784b to your computer and use it in GitHub Desktop.
Save intrnl/3f0e90aee377635a3dedaa4c7b07784b to your computer and use it in GitHub Desktop.
let map;
function generateUUID () {
const buf = crypto.getRandomValues(new Uint8Array(16));
buf[6] = (buf[6] & 0x0f) | 0x40;
buf[8] = (buf[8] & 0x3f) | 0x80;
if (!map) {
map = [];
for (let i = 0; i < 256; ++i) {
map.push((i + 256).toString(16).slice(1));
}
}
return (
map[buf[0]] +
map[buf[1]] +
map[buf[2]] +
map[buf[3]] +
'-' +
map[buf[4]] +
map[buf[5]] +
'-' +
map[buf[6]] +
map[buf[7]] +
'-' +
map[buf[8]] +
map[buf[9]] +
'-' +
map[buf[10]] +
map[buf[11]] +
map[buf[12]] +
map[buf[13]] +
map[buf[14]] +
map[buf[15]]
);
}
const uuidv4 = 'randomUUID' in crypto
? () => crypto.randomUUID()
: generateUUID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment