Skip to content

Instantly share code, notes, and snippets.

@gesslar
Last active August 21, 2020 05:18
Show Gist options
  • Save gesslar/52ea91f83b345b3d7ca547d6f4d43d70 to your computer and use it in GitHub Desktop.
Save gesslar/52ea91f83b345b3d7ca547d6f4d43d70 to your computer and use it in GitHub Desktop.
Password generator using ES5 JavaScript and the Fisher-Yates Algorithm
var config = {
numberToInclude: {
lowers : 3,
uppers : 2,
digits : 2,
symbols: 2
},
digits: "23456789",
symbols: "@#$%&*()[]~=",
lowers: "abcdefghjkmnpqrstuvwxyz",
uppers: "ABCDEFGHJKMNPQRSTUVWXWZ"
};
/**
* Randomize an array using the Fisher-Yates Algorithm method.
*
*/
var randomizeArray = function( element, index, array ) {
var pos = Math.floor( Math.random() * index );
var old = array[index];
var rand = array[pos];
array[index] = rand;
array[pos] = old;
};
/**
* Arrays to hold all the candidates for the password
*/
var digits = config.digits.split("");
var symbols = config.symbols.split("");
var lowers = config.lowers.split("");
var uppers = config.uppers.split("");
/**
* Randomize the candidate arrays
*/
digits.forEach( randomizeArray );
symbols.forEach( randomizeArray );
lowers.forEach( randomizeArray );
uppers.forEach( randomizeArray );
/**
* Construct the password array with the configured number of elements from
* each array
*/
var passwordArray = []
.concat( lowers.slice (0, config.numberToInclude.lowers) )
.concat( uppers.slice (0, config.numberToInclude.uppers) )
.concat( digits.slice (0, config.numberToInclude.digits) )
.concat( symbols.slice(0, config.numberToInclude.symbols) )
;
/**
* Randomize the final array
*/
passwordArray.forEach( randomizeArray );
/**
* Transform to a string and return it
*/
var password = passwordArray.join("");
console.log(password);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment