Skip to content

Instantly share code, notes, and snippets.

@sethdavis512
Last active May 13, 2024 15:33
Show Gist options
  • Save sethdavis512/42c7d7959aca57f47bf28c8a1c566c41 to your computer and use it in GitHub Desktop.
Save sethdavis512/42c7d7959aca57f47bf28c8a1c566c41 to your computer and use it in GitHub Desktop.
Get unique ID function
function getUniqueId(prefix: string, length: number = 8): string {
let result = `${prefix}-`;
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
let counter = 0;
while (counter < length) {
result = `${result}${characters.charAt(Math.floor(Math.random() * charactersLength))}`;
counter += 1;
}
return result;
};
function getUniqueId(
prefix: string = "my-prefix",
length: number = 8,
characters: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
): string {
const hash = [...Array(length)]
.map((_) =>
characters.charAt(Math.floor(Math.random() * characters.length))
)
.join("");
return `${!!prefix ? `${prefix}-` : ''}${hash}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment