Last active
May 13, 2024 15:33
-
-
Save sethdavis512/42c7d7959aca57f47bf28c8a1c566c41 to your computer and use it in GitHub Desktop.
Get unique ID function
This file contains hidden or 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
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