nupst/ts/helpers/shortid.ts

22 lines
686 B
TypeScript

/**
* Generate a short unique ID of 6 alphanumeric characters
* @returns A 6-character alphanumeric string
*/
export function shortId(): string {
// Define the character set: a-z, A-Z, 0-9
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// Generate cryptographically secure random values
const randomValues = new Uint8Array(6);
crypto.getRandomValues(randomValues);
// Map each random value to a character in our set
let result = '';
for (let i = 0; i < 6; i++) {
// Use modulo to map the random byte to a character index
const index = randomValues[i] % chars.length;
result += chars[index];
}
return result;
}