-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbigint.ts
More file actions
38 lines (36 loc) · 995 Bytes
/
bigint.ts
File metadata and controls
38 lines (36 loc) · 995 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
37
38
export const Alphabets = {
BASE36: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
};
export function encode(str: string, alphabet = Alphabets.BASE36): bigint {
if (str.length === 0) {
return 0n;
}
const base = BigInt(alphabet.length);
let value = 0n;
for (let i = 0; i < str.length; i++) {
const char = str[str.length - i - 1];
const charIndex = alphabet.indexOf(char);
if (charIndex === -1) {
throw new Error(`Invalid character: ${char}`);
}
value += BigInt(charIndex) * base ** BigInt(i);
}
return value;
}
export function decode(value: bigint, alphabet = Alphabets.BASE36): string {
const base = BigInt(alphabet.length);
let remaining = value;
if (remaining < 0n) {
throw new Error("Value must be positive");
}
if (remaining === 0n) {
return "0";
}
let str = "";
while (remaining > 0n) {
const charIndex = remaining % base;
remaining = remaining / base;
str = alphabet[Number(charIndex)] + str;
}
return str;
}