-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
48 lines (36 loc) · 1.02 KB
/
index.mjs
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
import { customAlphabet } from "nanoid";
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
export function fromBase33(char) {
const value = alphabet.indexOf(char) + 1; // +1 because index starts from 0
return value;
}
export function toBase33(num) {
let result = "";
while (num > 0) {
const remainder = num % 33;
result = alphabet.charAt(remainder) + result;
num = Math.floor(num / 33);
}
return result || "1"; // Return '1' if input is zero
}
export function calculateBase33Sum(id) {
let sum = 0;
for (let i = 0; i < id.length; i++) {
const char = id[i];
sum += fromBase33(char);
}
return sum;
}
export const generate = () => {
const nanoid = customAlphabet(alphabet, 12);
const baseId = nanoid();
const sum = calculateBase33Sum(baseId);
const b33Sum = toBase33(sum);
return baseId + b33Sum;
};
export const verify = (tag) => {
const baseId = tag.slice(0, -2);
const sum = calculateBase33Sum(baseId);
const b33Sum = tag.slice(-2);
return toBase33(sum) === b33Sum;
};