Last active
December 14, 2020 09:05
-
-
Save srph/1b23f4488f93954f98a8b30d2cdda53b to your computer and use it in GitHub Desktop.
JS: Generate a random string from a given characterset using only each character once
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 generateUnique(length) { | |
const generated = [] | |
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' | |
for (let i = 0; i < length; i++) { | |
let character = '' | |
do { | |
character = characters[random(characters.length)] | |
} while (generated.includes(character)) | |
generated.push(character) | |
} | |
return generated.join('') | |
} | |
function random(max) { | |
return Math.floor(Math.random() * max) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment