This is a special post for quick takes by Wei Dai. Only they can create top-level comments. Comments here also appear on the Quick Takes page and All Posts page.
I recommend against the use of Math.random() in general, unless you are highly performance constrained. I've checked, and it appears browsers have commonly supported a better random source since 2015[1]/early 2016 at the latest. The code below should be entirely correct to replace both the primary and fallback UUIDv4 generation code, once adapted to a function in a TS module.
// Function available since 2015.
const uuid_b = new Uint8Array(16);
self.crypto.getRandomValues(uuid_b);
let uuid_hex = "";
for (let i = 1; i <= 16; i++) {
let octet = uuid_b[i-1];
if (i == 9) {
// Set the correct "variant" (type).
octet = octet & 0xBF | 0x80
}
let o_hex = octet.toString(16);
// Branch on data.
if (o_hex.length == 1) {
// Big endian, least significant bits are
// on the right, therefore small numbers
// that only result in a single byte out
// need to be padded on the *left*.
o_hex = `0${o_hex}`
}
if (i == 7) {
// Set the correct version.
o_hex = "4" + o_hex[1]
}
uuid_hex = `${uuid_hex}${o_hex}`
if (i%2 == 0 && i > 3 && i < 11) {
uuid_hex = `${uuid_hex}-`
}
}
console.log(uuid_hex)
If that still won't work, I could help you do slightly better by manually implementing SHA3-256 in JavaScript, since we're not really worried about timing attacks at this level.