-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuuid.ts
More file actions
36 lines (32 loc) · 799 Bytes
/
Copy pathuuid.ts
File metadata and controls
36 lines (32 loc) · 799 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Parse a UUID string into a Uint8Array
*/
export function parseUuid(uuid: string): Uint8Array {
const hex = uuid.replace(/-/g, "");
if (!/^[0-9a-fA-F]{32}$/.test(hex)) {
throw new Error("Invalid UUID string");
}
const bytes = new Uint8Array(16);
for (let i = 0; i < 16; i++) {
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return bytes;
}
/**
* Format a Uint8Array into a UUID string
*/
export function formatUuid(bytes: Uint8Array): string {
if (bytes.length !== 16) {
throw new Error("UUID must be 16 bytes");
}
const hex = Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20),
].join("-");
}