Skip to content

Commit b28c815

Browse files
author
Steven-John Lange
committed
refactor: add uuidPolyfill
1 parent 2f64b0e commit b28c815

1 file changed

Lines changed: 40 additions & 2 deletions

File tree

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,41 @@
1-
export default function uuid() {
2-
return crypto.randomUUID();
1+
function uuidPolyfill() {
2+
const buffer = crypto.getRandomValues(new Uint8Array(16));
3+
4+
// https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
5+
// set bits for version: 4
6+
buffer[6] = (buffer[6] & 0x0f) | 0x40;
7+
// and variant: 1
8+
buffer[8] = (buffer[8] & 0x3f) | 0x80;
9+
10+
const str = toHex(buffer);
11+
12+
return str.slice(0, 8) + "-"
13+
+ str.slice(8, 12) + "-"
14+
+ str.slice(12, 16) + "-"
15+
+ str.slice(12, 16) + "-"
16+
+ str.slice(16, 20) + "-"
17+
+ str.slice(20);
318
}
19+
20+
/**
21+
* convert Uint8Array to HEX string
22+
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toHex
23+
*
24+
* @param {Uint8Array} buffer
25+
* @returns {string}
26+
*/
27+
function toHex(buffer) {
28+
if (typeof buffer.toHex === "function") {
29+
return buffer.toHex();
30+
}
31+
32+
let str = "";
33+
for (let i = 0; i < buffer.length; ++i) {
34+
str += buffer[i].toString(16).padStart(2, "0");
35+
}
36+
return str;
37+
}
38+
39+
const uuid = typeof crypto.randomUUID === "function" ? crypto.randomUUID.bind(crypto) : uuidPolyfill;
40+
41+
export default uuid;

0 commit comments

Comments
 (0)