ai-wpa/lib/siliconId.ts

37 lines
915 B
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 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 (0999)
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
}