-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathuuid.ts
More file actions
49 lines (47 loc) · 1.49 KB
/
uuid.ts
File metadata and controls
49 lines (47 loc) · 1.49 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
import { ULID_REGEX, UUID_REGEX } from "./constants.js";
import { crockfordDecode, crockfordEncode } from "./crockford.js";
import { ULIDError, ULIDErrorCode } from "./error.js";
import { ULID } from "./types.js";
/**
* Convert a ULID to a UUID
* @param ulid The ULID to convert
* @returns A UUID string
*/
export function ulidToUUID(ulid: ULID): string {
const isValid = ULID_REGEX.test(ulid);
if (!isValid) {
throw new ULIDError(ULIDErrorCode.ULIDInvalid, `Invalid ULID: ${ulid}`);
}
const uint8Array = crockfordDecode(ulid);
let uuid = Array.from(uint8Array)
.map(byte => byte.toString(16).padStart(2, "0"))
.join("");
uuid =
uuid.substring(0, 8) +
"-" +
uuid.substring(8, 12) +
"-" +
uuid.substring(12, 16) +
"-" +
uuid.substring(16, 20) +
"-" +
uuid.substring(20);
return uuid.toUpperCase();
}
/**
* Convert a UUID to a ULID
* @param uuid The UUID to convert
* @returns A ULID string
*/
export function uuidToULID(uuid: string): ULID {
const isValid = UUID_REGEX.test(uuid);
if (!isValid) {
throw new ULIDError(ULIDErrorCode.UUIDInvalid, `Invalid UUID: ${uuid}`);
}
const bytes = uuid.replace(/-/g, "").match(/.{1,2}/g);
if (!bytes) {
throw new ULIDError(ULIDErrorCode.Unexpected, `Failed parsing UUID bytes: ${uuid}`);
}
const uint8Array = new Uint8Array(bytes.map(byte => parseInt(byte, 16)));
return crockfordEncode(uint8Array);
}