Last active
February 9, 2021 13:59
-
-
Save joshuaebowling/7fafd0e7f0c21169aa636bf350e75828 to your computer and use it in GitHub Desktop.
TS create random string custom length custom prefix
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
const alphanum = "aAbBcCdDeEfFgGHhIIJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789".split(""); | |
export const random: (size: number, prefix: string | null) => string = (size, prefix = null) => { | |
if(prefix && prefix.length > size) return throw("size must be greater than prefix length") | |
const result = []; | |
for (let i = 0; i < size; i++) { | |
result.push(alphanum[Math.floor(Math.random() * alphanum.length)]); | |
} | |
const base = result.join(""); | |
if (!prefix) return base; | |
return `${prefix}:${base.substr(0, base.length - prefix.length)}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment