Last active
January 15, 2019 21:57
-
-
Save tobiamos/396ec5b5fd77a935fbe43ec64892b83e to your computer and use it in GitHub Desktop.
generate unique strings
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 HashID = {}; | |
HashID.generate = () => { | |
const alphabet = '23456789abdegjkmnpqrvwxyz'; | |
const idLength = 9; | |
let result = ''; | |
for (let index = 0; index < idLength; index += 1) { | |
result += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); | |
} | |
return result; | |
}; | |
HashID.generateUnique = (previous = []) => { | |
let retries = 0; | |
const maxRetries = 9999; | |
let id; | |
while (!id && retries < maxRetries) { | |
id = HashID.generate(); | |
if (previous.includes(id)) { | |
id = null; | |
retries += 1; | |
} | |
} | |
return id; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank man