Skip to content

Instantly share code, notes, and snippets.

@flockonus
Last active January 20, 2025 21:51
Show Gist options
  • Save flockonus/6af9218328437a5eb2d02cd6c494ca37 to your computer and use it in GitHub Desktop.
Save flockonus/6af9218328437a5eb2d02cd6c494ca37 to your computer and use it in GitHub Desktop.
Efficient (non-standard) UUID
// -> output range == equal max safe integer (~ 4 quadrillion)
// output string efficiency could be better, also first digit is often `1`
function randomString() {
const randomNum = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); // Generate a single random number
const boundedString = randomNum.toString(36); // Convert to base36 string
return boundedString;
}
const ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
const ALPHABET_ARRAY = Uint8Array.from(ALPHABET, (char) => char.charCodeAt(0))
const ALPHABET_LENGTH = ALPHABET_ARRAY.length
/**
* Generates a random Base58 string.
* @param length The length of the generated string. Defaults to 8.
* @returns A random Base58 string.
*/
export function randomBase58(length: number = 8): string {
const result = new Array(length)
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * ALPHABET_LENGTH)
result[i] = String.fromCharCode(ALPHABET_ARRAY[randomIndex])
}
return result.join("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment