Skip to content

Instantly share code, notes, and snippets.

@zgover
Last active December 12, 2020 20:48
Show Gist options
  • Save zgover/1ff524235f46a23c640f752217e0d14a to your computer and use it in GitHub Desktop.
Save zgover/1ff524235f46a23c640f752217e0d14a to your computer and use it in GitHub Desktop.
Base36 Random UID Generator
/**
* Generate a random ID string
*
* Math.random should be unique because of its seeding algorithm.
* Convert it to base 36 (numbers + letters) and grab the first 9 characters
* after the decimal.
*
* @param config {RandomIdConfig}
*
* @return {string}
*/
function base36Id(opt?: RandomIdConfig): string {
const { prefix, radix, maxLength } = opt ?? {}
const id = Math.random()
.toString(radix ?? 36)
.substr(2/* e.g. first digit & decimal `0.` */, maxLength ?? 9)
return String().concat(prefix ?? '', id)
}
type RandomIdConfig = {
prefix?: string
radix?: number
maxLength?: number
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment