I'm creating a random password generator, and it's working well. However, I've noticed that my generatePassword()
function doesn't always pull from each array when the condition for each if
statement is true. For example:
function generatePassword() {
// The arrays below are the arrays from which my generatePassword function can pull characters.
const lowercase = ["a", "b", "c", "d", "e", "f", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
const uppercase = ["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", "X"];
let charSet = [];
const passLength = prompt("Choose a length for your password. (This should be any amount between 8 and 128 characters.)");
if (!isNaN(passLength) && passLength >= 8 && passLength <= 128) {
const passLc = confirm("Should the password contain lowercase letters?");
if (passLc) {
for(let i = 0; i < lowercase.length; i ) {
charSet.push(lowercase[i]);
}
}
const passUc = confirm("Should the password contain uppercase letters?");
if (passUc) {
for(let i = 0; i < uppercase.length; i ) {
charSet.push(uppercase[i]);
}
}
} else {
prompt("Sorry, that entry is invalid. Please enter a value between 8 and 128.");
}
console.log(charSet);
return password;
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
Is there a way to ensure that my function pulls from each array when the user's answer is true for each condition? Thank you in advance!
EDIT: Apologies for the confusion!
- The
charSet
array is a blank array that I'm using to compile an array of all of my smaller array indexes, and then using that to pull random characters. - As far as I understand it, the purpose of getRandomInt is to pull random index items for the
randomIndex
constant from thecharSet
array.
CodePudding user response:
As far as I understand your question you need to have 1 more if statement that will run when both passUc and passlc are true like this
const passLc = confirm("Should the password contain lowercase letters?");
const passUc = confirm("Should the password contain uppercase letters?");
if(passUc && passLc){
for(let i = 0; i < lowercase.length; i ) {
charSet.push(uppercase[i]);
charSet.push(lowercase[i]);
}
}
else if (passLc) {
for(let i = 0; i < lowercase.length; i ) {
charSet.push(lowercase[i]);
}
}
else if (passUc) {
for(let i = 0; i < uppercase.length; i ) {
charSet.push(uppercase[i]);
}
}
In case you don't use new if statement your code will just generate a password greater then passLength.
CodePudding user response:
I think I have come across a cleaner code to generate password:
Math.random().toString(36).slice(2, 10)