Last active
December 12, 2020 20:48
-
-
Save zgover/1ff524235f46a23c640f752217e0d14a to your computer and use it in GitHub Desktop.
Base36 Random UID Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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