37 lines
837 B
TypeScript
37 lines
837 B
TypeScript
// Simple ULID generator
|
|
// ULID format: 01234567890123456789012345 (26 characters)
|
|
// Time (10 chars) + Random (16 chars)
|
|
|
|
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
const TIME_LEN = 10;
|
|
const RANDOM_LEN = 16;
|
|
|
|
const getRandomChar = (): string => {
|
|
return ENCODING[Math.floor(Math.random() * ENCODING.length)];
|
|
};
|
|
|
|
const encodeTime = (now: number): string => {
|
|
let time = "";
|
|
let num = now;
|
|
|
|
for (let i = 0; i < TIME_LEN; i++) {
|
|
time = ENCODING[num % ENCODING.length] + time;
|
|
num = Math.floor(num / ENCODING.length);
|
|
}
|
|
|
|
return time;
|
|
};
|
|
|
|
const encodeRandom = (): string => {
|
|
let random = "";
|
|
for (let i = 0; i < RANDOM_LEN; i++) {
|
|
random += getRandomChar();
|
|
}
|
|
return random;
|
|
};
|
|
|
|
export const generateULID = (): string => {
|
|
const now = Date.now();
|
|
return encodeTime(now) + encodeRandom();
|
|
};
|