-3

I want to change all the if else statements to ternary operator. Whats the ternary operator for this if else statements ?

  const compareHands = (playerChoice, computerChoice) => {
        // Update Text
        const winner = document.querySelector('.winner');
        const winnerIs = (who, isPlayerWin) => {

            winner.textContent = `${who} Wins!`;

            isPlayerWin ? pScore++ : cScore++;

            updateScore();
        };



        // Check for tie
        if (playerChoice === computerChoice) {
            winner.textContent = 'It Is A Tie!';
            // Check For Winner
        } else if (playerChoice === 'rock') {
            if (computerChoice === 'scissors') {
                winnerIs('Player', true);
            } else {
                winnerIs('Computer', false);
            }
        } else if (playerChoice === 'paper') {
            if (computerChoice === 'scissors') {
                winnerIs('Computer', false);
            } else {
                winnerIs('Player', true);
            }
        } else if (playerChoice === 'scissors') {
            if (computerChoice === 'rock') {
                winnerIs('Computer', false);
            } else {
                winnerIs('Player', true);
            }
        }
    }
HorrorRice
  • 33
  • 1
  • 5

5 Answers5

1

Honestly, I don't think the use of ternary operator will make the code better. I suggest the you try to reduce the if-else chain by creating a data structure for easy look up, something like this:


const whatBeats = {
  'scissors': 'rock',
  'paper': 'scissors',
  'rock': 'paper'
};
const compareHands = (playerChoice, computerChoice) => {
  // Update Text
  const winner = document.querySelector('.winner');
  const winnerIs = (who, isPlayerWin) => {

    winner.textContent = `${who} Wins!`;

    isPlayerWin ? pScore++ : cScore++;

    updateScore();
  };

  // Check for tie
  if (playerChoice === computerChoice) {
    winner.textContent = 'It Is A Tie!';
    // Check For Winner
  } else if (playerChoice === whatBeats[computerChoice]) {
    winnerIs('Player', true);
  } else {
    winnerIs('Computer', false)
  }
}

In this case, we are treating the game dynamics as data, centralizing it on one place.

For the next questions, try to solve the problem before (there are tons of tutorial regarding ternary operators).

0

Try like this. Though readability is a problem since there are too many nested if else which is replaced by ternary operator. true & false are replace with !0 & !1 respectively to shorten the statement

playerChoice === computerChoice ?
  winner.textContent = "It Is A Tie!" :
  "rock" === playerChoice ?
  "scissors" === computerChoice ?
  winnerIs("Player", !0) :
  winnerIs("Computer", !1) :
  "paper" === playerChoice ?
  "scissors" === computerChoice ?
  winnerIs("Computer", !1) :
  winnerIs("Player", !0) :
  "scissors" === playerChoice && ("rock" === computerChoice ? winnerIs("Computer", !1) :
    winnerIs("Player", !0));
brk
  • 48,835
  • 10
  • 56
  • 78
  • @AKX there is always a better way than the best. I just answered the question which the SO user asked. I could have suggest him object mapping instead of nested if.. else which people have already done , but that not the answer to his question – brk Apr 11 '19 at 08:12
  • @brk Yeah, I didn't mean it as criticism – you do answer the OP's question, it's just that no one should really do this in "production" :) – AKX Apr 11 '19 at 08:13
0

As Nina Scholz says, I would not use either. I know this does not answer the literal question, but how about this instead?

const loser_to = {
  paper: 'rock',
  rock: 'scissors',
  scissors: 'paper'
};

if (loser_to[playerChoice] === computerChoice) {
  // player wins
} else if (loser_to[computerChoice] === playerChoice) {
  // computer wins
} else {
  // noone wins
}
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Using too many ternary could lead to unreadable code. I suggest you can use switch case combining with ternary operators.

switch (playerChoice) {
   case computerChoice: winner.textContent = 'It Is A Tie!';break;
   case 'rock': computerChoice === 'scissors' ?  winnerIs('Player', true) : winnerIs('Computer', false); break;
   case 'paper': computerChoice === 'rock' ?  winnerIs('Player', true) : winnerIs('Computer', false); break;
   case 'scissors': computerChoice === 'paper' ?  winnerIs('Player', true) : winnerIs('Computer', false); break;
    }
Nhon Dinh
  • 221
  • 1
  • 5
0

If you want a much more DRYied code. You could try this solution to avoid multiple call of winnerIs function.

const compareHands = (playerChoice, computerChoice) => {
  const winner = document.querySelector('.winner');

  if (playerChoice == computerChoice) {
    winner.textContent = 'It Is A Tie!';
    return;
  }

  let choices = ['rock', 'paper', 'scissor'];
  let playerIndex, computerIndex, isPlayerWin;

  playerIndex = choices.indexOf(playerChoice);
  choices.push(choices.shift());
  computerIndex = choices.indexOf(computerChoice);
  isPlayerWin = playerIndex !== computerIndex;

  winner.textContent = `${isPlayerWin ? 'Player' : 'Computer'} Wins!`;
  isPlayerWin ? pScore++ : cScore++;
  updateScore();
}