Home > Software engineering >  How to setup conditional logic based on if an Object's values are either false or true? (Passwo
How to setup conditional logic based on if an Object's values are either false or true? (Passwo

Time:01-07

The program is a password generator that allows the user to choose if they would like lowercase, uppercase, numeric and special characters as part of their password. Each respective choice is stored in an array of their charsets.

I have managed to create the program and it runs as intended if all options are true. The options are stored as variables from confirm(). I then took all these variables and stored them in an object for easy referencing.

Unfortunately, I am unable to execute the program when any of the conditions are false. I cannot work out the logic for the program to still execute and ignore the false conditions, only providing options from the variables that are true. I think my logic to generate the password using the options is where I am going wrong. Aside from using multiple if/else branches to evaluate each possible combination, I can't find a way to do this in a DRY way.

// Function to prompt user for password options
function getPasswordOptions() {
 
  var passwordLength;
  do {
    passwordLength = parseInt(prompt("How many characters would you like in your password (between 10 and 64)?"));
  } while (passwordLength < 10 || passwordLength > 64);

  // All the prompts for the type of password options that the user would like.
  var lowercase = confirm("Would you like lowercase characters in your password?");
  var uppercase = confirm("Would you like uppercase characters in your password?");
  var special = confirm("Would you like special characters in your password?");
  var numbers = confirm("Would you like numbers in your password?");

  var userPasswordOpts = {
    plength: passwordLength,
    opt1: lowercase,
    opt2: uppercase,
    opt3: special,
    opt4: numbers
  };

  return userPasswordOpts;
}

// Function for getting a random element from an array
function getRandom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

// Function to generate password with user input
function generatePassword() {
  var userPasswordChoice = getPasswordOptions();
  var passwordArr = [];

  if (Object.values(userPasswordChoice)) {
    for (var i = 0; i < userPasswordChoice.plength; i  ) {

      var randomNum = Math.floor(Math.random() * 3)   1;

      switch(randomNum) {
        case 1:
          passwordArr.push(getRandom(lowerCasedCharacters));
        break;
        case 2:
          passwordArr.push(getRandom(upperCasedCharacters));
        break;
        case 3:
          passwordArr.push(getRandom(specialCharacters));
        break;
        case 4:
          passwordArr.push(getRandom(numericCharacters));
        default:
          null;
      }
    }
  }
  return passwordArr.join('');
}

CodePudding user response:

To answer your question, (probably not the best "DRY" way):

  1. add something like trueCount : Notice I also added an optionsArr with the options you had, and filter it for chosen options as per the input.

    ... var passwordArr = []; trueCount = Object.values(userPasswordChoice).filter(x => x==true).length; optionsArr = [lowerCasedCharacters, upperCasedCharacters, specialCharacters, numericCharacters]; chosenOptions = optionsArr.filter(x=> Object.values(userPasswordChoice)[optionsArr.indexOf(x) 1]); if (Object.values(userPasswordChoice)) { ...

  2. replaced the "3" by trueCount, because that's how many cases we are going to try

  3. Modify your switch cases as such:

    ... var randomNum = Math.floor(Math.random() * trueCount) 1; switch(randomNum) { case 1: passwordArr.push(getRandom(chosenOptions[0])); break; ...

PS, I am pretty sure the if condition : Object.values(userPasswordChoice) which is an array, will always evaluate to true.

CodePudding user response:

There is always better way to write an algorithim, but I am sharing below code to give you some idea.

function getRandom(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i   1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

function generatePassword(passwordLength, userPasswordChoice) {
  const passwordArr = [];
  const charSets = {
    lower: ['a','b','c'],
    upper: ['A', 'B', 'C'],
    special: ['@','#','!'],
    numeric: [1,2,3],
  }
  
  if (Object.values(userPasswordChoice)) {
  
    let chatSetArr = [];
    const charSetTypes = Object.keys(userPasswordChoice).filter(charSetType => userPasswordChoice[charSetType]);
    for (var i = 0; i < passwordLength; i  ) {
      chatSetArr.push(...charSetTypes);
    }
    chatSetArr = chatSetArr.slice(chatSetArr.length-passwordLength);
    shuffleArray(chatSetArr);

    return chatSetArr.map(charSet => getRandom(charSets[charSet])).join('');
  }
  return '';
}

console.log(generatePassword(12, 
  {
    lower: true,
    upper: true,
    special: true,
    numeric: true,
  }));
  
console.log(generatePassword(12, 
  {
    lower: false,
    upper: true,
    special: true,
    numeric: false,
  }));

  • Related