Last active
August 21, 2020 05:27
-
-
Save gesslar/bb1fa2e4980331b6935f8dbb1682a1de to your computer and use it in GitHub Desktop.
Password generator using ES6 JavaScript and the Fisher-Yates Algorithm
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 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. | |
* | |
*/ | |
const randomizeArray = ( element, index, array ) => { | |
const pos = Math.floor( Math.random() * index ); | |
const old = array[index]; | |
const rand = array[pos]; | |
array[index] = rand; | |
array[pos] = old; | |
} | |
/** | |
* Arrays to hold all the candidates for the password | |
*/ | |
const digits = config.digits.split(""); | |
const symbols = config.symbols.split(""); | |
const lowers = config.lowers.split(""); | |
const 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 | |
*/ | |
const 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 | |
*/ | |
const password = passwordArray.join(""); | |
console.log(password); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment