Skip to content

Instantly share code, notes, and snippets.

@unascribed
Last active October 5, 2023 11:35
Show Gist options
  • Save unascribed/8dff33de78cfc604bb421a9cbcb68a4b to your computer and use it in GitHub Desktop.
Save unascribed/8dff33de78cfc604bb421a9cbcb68a4b to your computer and use it in GitHub Desktop.
A simple and readable way to generate valid v4 UUIDs in JavaScript. CC0 https://creativecommons.org/publicdomain/zero/1.0/
function randomUUID() {
return randhex(8) + "-" + randhex(4) + "-4" + randhex(3) + "-" + choice(["8", "9", "a", "b"]) + randhex(3) + "-" + randhex(12);
}
let scratchTarr = new Uint32Array(1);
function choice(arr) {
crypto.getRandomValues(scratchTarr);
return arr[Math.floor(scratchTarr[0]%arr.length)]
}
function randhex(count) {
crypto.getRandomValues(scratchTarr);
return ("00000000"+scratchTarr[0].toString(16)).slice(-count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment