(size = 21, alphabet: string = URL_SAFE_ALPHABET)
| 44 | * @returns A random string drawn from the alphabet |
| 45 | */ |
| 46 | export function generateShortId(size = 21, alphabet: string = URL_SAFE_ALPHABET): string { |
| 47 | const alphabetLength = alphabet.length |
| 48 | if (alphabetLength < 2 || alphabetLength > 256) { |
| 49 | throw new Error('generateShortId alphabet length must be between 2 and 256') |
| 50 | } |
| 51 | |
| 52 | const mask = (2 << (31 - Math.clz32((alphabetLength - 1) | 1))) - 1 |
| 53 | const step = Math.ceil((1.6 * mask * size) / alphabetLength) |
| 54 | |
| 55 | let id = '' |
| 56 | while (id.length < size) { |
| 57 | const bytes = new Uint8Array(step) |
| 58 | crypto.getRandomValues(bytes) |
| 59 | for (let i = 0; i < step && id.length < size; i++) { |
| 60 | const index = bytes[i] & mask |
| 61 | if (index < alphabetLength) { |
| 62 | id += alphabet[index] |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | return id |
| 67 | } |
no outgoing calls