Skip to content

Instantly share code, notes, and snippets.

@marlun78
Created July 19, 2018 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlun78/1f33b67ff202da86a960b62988357e74 to your computer and use it in GitHub Desktop.
Save marlun78/1f33b67ff202da86a960b62988357e74 to your computer and use it in GitHub Desktop.
Samples a given number of characters from a given string
// 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