Created
July 19, 2018 12:45
-
-
Save marlun78/1f33b67ff202da86a960b62988357e74 to your computer and use it in GitHub Desktop.
Samples a given number of characters from a given string
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
// sample.js | |
// Samples a given number of characters from a given string. | |
// Example; | |
// sample('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 4); // Eg. 'uY7m' | |
function sample(characters, length) { | |
var result = ''; | |
for (var i = 0; i < length; i++) { | |
result += getRandomChar(characters); | |
} | |
return result; | |
} | |
function getRandomChar(characters) { | |
return characters[getRandomInteger(characters.length)]; | |
} | |
function getRandomInteger(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