Skip to content

Instantly share code, notes, and snippets.

@pedroglcbarros
Last active October 29, 2021 14:04
Show Gist options
  • Select an option

  • Save pedroglcbarros/86989c27cb8374062ef888a219427972 to your computer and use it in GitHub Desktop.

Select an option

Save pedroglcbarros/86989c27cb8374062ef888a219427972 to your computer and use it in GitHub Desktop.
Function to generate password
// USING ARRAY
function generatePassword(passwordLength) {
const components = [
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
[0,1,2,3,4,5,6,7,8,9],
["!", "#", "$", "%", "&", "/", "*", "~", "^", "+", "-",".", "?", "@", "(", ")","[", "]", "{", "}",":", ";"]
]
const password = [];
for(let i = 1; i <= passwordLength; i++) {
let randComponent = components[Math.floor(Math.random() * components.length)];
let randItem = randComponent[Math.floor(Math.random() * randComponent.length)];
password.push(randItem);
}
return password.join("")
}
// USING OBJECT
function generatePassword(passwordLength) {
const components = {
lowerCaseLetters: ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],
upperCaseLetters: ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
symbols: ["!","#","$","%","&","/","*","~","^","+","-",".","?","@","(",")","[","]","{","}",":",";"]
};
const password = [];
for (let i = 1; i <= passwordLength; i++) {
let randComponent = Object.keys(components)[Math.floor(Math.random() * Object.keys(components).length)];
let randItem = components[randComponent][Math.floor(Math.random() * randComponent.length)];
password.push(randItem);
}
return password.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment