37 lines
915 B
TypeScript
37 lines
915 B
TypeScript
/**
|
||
* Encode number to Base62
|
||
*/
|
||
function toBase62(num: number): string {
|
||
const base62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
||
let encoded = ''
|
||
let n = num
|
||
if (n === 0) return '0'
|
||
|
||
while (n > 0) {
|
||
encoded = base62[n % 62] + encoded
|
||
n = Math.floor(n / 62)
|
||
}
|
||
return encoded
|
||
}
|
||
|
||
/**
|
||
* Generate compact Silicon ID
|
||
* Format: base62(timestamp + random), min length 8 chars
|
||
*/
|
||
export function generateSiliconId(): string {
|
||
const epochStart = new Date('2020-01-01').getTime()
|
||
const now = Date.now()
|
||
|
||
// relative timestamp since epochStart
|
||
const timestamp = (now - epochStart) % 1_000_000_000_000
|
||
|
||
// add randomness (0–999)
|
||
const randomNum = Math.floor(Math.random() * 1000)
|
||
|
||
// combine into one big number
|
||
const finalNum = timestamp * 1000 + randomNum
|
||
|
||
// convert to base62
|
||
return toBase62(finalNum).padStart(10, '0') // always at least 10 chars
|
||
}
|