mortvicious
mortvicious

Reputation: 109

function: if with interrupting, return

I am not able to get values from my prompt function

I need the function to work properly if users input is equal to one of 6 variables, and in "if" condition to stop if input didn't match any. I manipulated with &&, || !, ==, === a lot, nothing works, console.log gives me the same result I'm typing (but with upper cased first letter, lol)

//variables
let r = "Rock";
let p = "Paper";
let s = "Scissor";
let rl = "rock";
let pl = "paper";
let sl = "scissor";
const weapon = [r, p, s];
let playerChoiceUnchecked = prompt("Rock, Paper, or Scissor?");
//functions
function playerChoice(checkPlayer) {
 if (playerChoiceUnchecked == ((!r && !rl) && (!p && !pl) && (!s && !sl))) {
    alert("There's no such weapon");
    return false;
 } else {
    let checkPlayer = playerChoiceUnchecked.charAt(0).toUpperCase() + playerChoiceUnchecked.slice(1);
    //return checkPlayer;
    console.log(checkPlayer); //debug for playerChoice, second part DONE
 }
}

Upvotes: 1

Views: 51

Answers (2)

Leo Rossetti
Leo Rossetti

Reputation: 185

If I understood your question, you want a function to validate if the option is valid. If that's the case, you can do this in multiple ways. Here are two more simple ways to do this:

1st: (Call this function and see if the option is valid. The function will return true = valid / false = invalid)

function verifyOptionSelected(option){
    var isValid = false;
    if (option != null){
        switch(option.toLowerCase()){
            case "rock":
            case "paper":
            case "scissor":
                isValid = true;
                break;
            default:
                isValid = false;
        }
    }

    return isValid;
}

2nd: (same method, but better way to code it, in my opinion)

function verifyOptionSelected(option){
    var validOptions = ["rock", "paper", "scissor"];
    return option != null && validOptions.indexOf(option.toLowerCase()) >= 0;    
}

Upvotes: 1

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

Your code could be simplified:

const weapons = ["rock", "paper", "scissor"]

function playerChoice() {
  let playerChoiceUnchecked = prompt("Rock, Paper, or Scissor?");
  if ( !weapons.includes( playerChoiceUnchecked.toLowerCase() ) ) {
    alert("There's no such weapon");
  } else {
    let checkPlayer = playerChoiceUnchecked.charAt(0).toUpperCase() + playerChoiceUnchecked.slice(1);
    console.log(checkPlayer);
  }
}

playerChoice()

Upvotes: 1

Related Questions