Skip to content

Instantly share code, notes, and snippets.

@joshuaebowling
Last active February 9, 2021 13:59
Show Gist options
  • Save joshuaebowling/7fafd0e7f0c21169aa636bf350e75828 to your computer and use it in GitHub Desktop.
Save joshuaebowling/7fafd0e7f0c21169aa636bf350e75828 to your computer and use it in GitHub Desktop.
TS create random string custom length custom prefix
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