Reputation: 3
Appreciate any answers to this conumdrum in advance !
I have a function to generate password which takes in a number of options chosen by a user via prompts and confirms - one of these prompts returns a password length and all these options are stored within an options object i get access to using dot notation within this function.
I need to generate a bunch of characters which have been determined by the users choices - it needs to be only the length the user has entered in the prompt.
In this case i've decided to have a loop where a password lengths condition is met and at each iteration the body of the if statement should execute a getRandom function which will return a single random character from array passed to it as an argument to function.
However on testing my code - i can not get the if statements to only execute only the number of times the user has entered as the password length.
How do i achieve this with a while loop or any other loop.
function generatePassword() {
const optSelected = getPasswordOptions();
let generatedPassArr = [];
const passwordLength = optSelected.passwordLength;
let counter = 0;
let lowercaseCounted;
let uppercaseCounted;
let numbersCounted;
let specialsCounted;
while (counter < passwordLength) {
if (optSelected.lowercase && !lowercaseCounted) {
console.log("execute random function lowercase");
lowercaseCounted = true;
} else {
break;
}
if (optSelected.uppercase && !uppercaseCounted) {
console.log("execute random function uppercase");
uppercaseCounted = true;
}
if (optSelected.numbers && !numbersCounted) {
console.log("execute random function numbers");
numbersCounted = true;
}
if (optSelected.specials && !specialsCounted) {
console.log("execute random function specials");
specialsCounted = true;
}
console.log("testing");
counter++;
}
console.log(generatedPassArr);
}
As you can see i have attempted to create variables so that each if statement does not repeat continously in a block - rather i need atleast the if block to execute once - if the object property exists true, until the loop reaches the password length.
Upvotes: 0
Views: 495
Reputation: 2442
Unless you have a specific need to use a while
loop here (i.e. this is an assignment) have you considered using regex to test this instead?
With a singular regex for each password criteria, I think you could avoid the use of the while
loop altogether.
Upvotes: 1