Ternary Condition for if { } else if { if { } else { } } - javascript

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);
}
}
}

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).

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));

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
}

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;
}

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();
}

Related

Beginners first try at coding rock, paper.. game. Keeps returning 'paper wins'

I keep getting 'paper wins' when I enter 'rock' as my choice.
function game() {
pChoice = prompt('What is your play?');
cChoice = ['rock','paper','scissor'];
let compChoice = [Math.floor(Math.random() * cChoice.length)];
console.log(compChoice);
function compare(pChoice, compChoice) {
if (pChoice === compChoice) {
alert( "It's a tie" );
}
if (pChoice === 'rock') {
if (compChoice === 'scissor') {
return 'rock wins';
} else {
return 'paper wins';
}
}
else if (pChoice === 'paper') {
if (compChoice === 'rock') {
return 'paper wins';
} else {
return 'scissor wins';
}
}
else if (pChoice === 'scissor') {
if (compChoice === 'paper') {
return 'scissor wins';
} else {
return 'rock wins';
}
}
}
var result = compare(pChoice, compChoice);
console.log(compare(pChoice, compChoice));
}
game();
You never assign cChoice to a value, instead you are assigning it to an array with a number in it.
For example:
// Assigning to [number]
let compChoice = [Math.floor(Math.random() * cChoice.length)];
// Assigning to string inside of array cChoice
let compChoice = cChoice[Math.floor(Math.random() * cChoice.length)];

Tie result cannot be outputted

While creating the rock, paper, scissors application, I am tasked to output specific results in the console, such as outputting paper-paper and receive 'It's a tie' result. Well, I have tried to do that but for some reason, I cannot do so. The code is as below:
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
const winner = () => {
const choice1 = user('rock');
const choice2 = computer();
if(choice1 === choice2) {
return 'It\'s a tie!';
}
if(choice1 === 'rock') {
if(choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'paper') {
if(choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if(choice1 === 'scissors') {
if(choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
}
console.log(winner('paper', 'paper'));
When I try to type console.log(winner('paper', 'paper')) for example, the result is random meaning that it can be either win, lost or tie due to the fact (or what I suppose is the reason) that the computer's choice is random but this is how I am asked to create the computer's choice. If I type console.log(('paper', 1)) I get the same result but somehow, the task is asking me to use console.log(winner('paper', 'paper')) and is telling me that the result should be a tie. I have also tried to let the user with no parameter in choice1 but I get an error due to the fact that there is no input in the user's choice.
The tasks are as below:
console.log(determineWinner('paper', 'scissors')); // prints something like 'The computer won!'
console.log(determineWinner('paper', 'paper')); // prints something like 'The game is a tie!'
console.log(determineWinner('paper', 'rock')); // prints something like 'The user won!'
Any help or idea would be appreciated. Thanks!
Something like this would work. If It is what you need.
const user = userInput => {
userInput = userInput.toLowerCase();
if(userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
} else {
console.log('error');
}
}
function computer() {
const random = Math.floor(Math.random() * 3);
switch(random){
case 0 : return 'rock';
break;
case 1 : return 'paper';
break;
default : return 'scissors';
}
};
// Here is where you need to change something
const determineWinner = (userChoice, computerChoice) => {
// And use the parameters here:
const choice1 = userChoice;
const choice2 = computerChoice;
if (choice1 === choice2) {
return 'It\'s a tie!';
}
if (choice1 === 'rock') {
if (choice2 === 'paper') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'paper') {
if (choice2 === 'scissors') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
if (choice1 === 'scissors') {
if (choice2 === 'rock') {
return 'Computer wins!';
} else {
return 'You win!';
}
}
};
const userInput = 'rock';
console.log(determineWinner(user(userInput), computer()));
console.log(determineWinner('rock', 'paper'));
console.log(determineWinner('paper', 'paper'));
// For you requirement:
console.log(determineWinner('paper', 'scissors'));
console.log(determineWinner('paper', 'paper'));
console.log(determineWinner('paper', 'rock'));
But if you hardcode the parameters as you requirement suggests then your functions user and computer are not used.

Javascript throws undefined

So i've been trying to learn to code and have been using codeAcademy as as resource. I'm currently doing a Rock, Paper, Scissors exercise and my code runs fine but my last console.log(determineWinner(userChoice, computerChoice));" throws an undefined into the console. Any help would be appreciated.
const getUserChoice = (userInput) => {
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
return userInput;
} else {
console.log('Error!');
}
}
const getComputerChoice = () => {
switch (Math.floor(Math.random() * 3)) {
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
const determineWinner = (userChoice, computerChoice) => {
if (getUserChoice === getComputerChoice) {
return 'the game was a tie';
}
}
if (getUserChoice === 'rock') {
if (getComputerChoice === 'paper') {
return 'computer won!';
} else {
return 'you won!';
}
}
if (getUserChoice === 'paper') {
if (getComputerChoice === 'scissors') {
return 'computer won!';
} else {
return 'you won!';
}
}
if (getUserChoice === 'scissors') {
if (getComputerChoice === 'rock') {
return 'computer won!';
} else {
return 'you won!';
}
}
const playGame = () => {
const userChoice = getUserChoice('rock');
const computerChoice = getComputerChoice();
console.log(`You threw: ${userChoice}`);
console.log(`The computer threw: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
};
playGame();
Ignoring a small syntax mistake in the code you posted here, the problem with the non-working code is that in the function determineWinner, you've two variables named userChoice and computerChoice. But, wrongly, you are using getUserChoice and getComputerChoice.
const getUserChoice = (userInput) => {
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
return userInput;
} else {
console.log('Error!');
}
}
const getComputerChoice = () => {
switch (Math.floor(Math.random() * 3)) {
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return 'the game was a tie';
}
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'computer won!';
} else {
return 'you won!';
}
}
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'computer won!';
} else {
return 'you won!';
}
}
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'computer won!';
} else {
return 'you won!';
}
}
}
const playGame = () => {
const userChoice = getUserChoice('rock');
const computerChoice = getComputerChoice();
console.log(`You threw: ${userChoice}`);
console.log(`The computer threw: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
};
playGame();

ReferenceError: prompt is not defined - Rock, Paper, or Scissors

I am experiencing some issues to finish this code.
ReferenceError: prompt is not defined
at Object. //(/home/ccuser/workspace/javascript_101_Unit_3/Unit_3/rockPaperScissors.js:1:80) this is the first error, I tried not to use prompt, and just calling the code at the end, but I need some advice on what is the best practice for that.
Could someone give tips to improve this code?
let userPrompt = prompt("enter a choice: ");
const getUserChoice = userPrompt => {
if (userInput === 'rock' || userInput === 'Paper' || userInput === 'scissors') {
return userInput;
} else {
console.log('Error');
}
}
const randomNumber = 'Math.floor(Math.random() * 3)';
switch (randomNumber) {
case 0:
return 'rock';
// I don't know if I have to have a break here.
case 1:
return 'Paper';
case 2:
return 'scissors';
case 3:
return 'bomb';
}
console.log(getUserChoice());
function determineWinner(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return 'the game is a tie';
}
if (userChoice === 'bomb') {
return 'You won!'; /* add a fourth condition that checks if the userInput is 'bomb'.At the beginning of determineWinner(), add another if statement that makes the user win if the userChoice is 'bomb'.*/
}
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'The computer won!';
} else {
return 'You won!';
}
} else if (userChoice === 'Paper') {
if (computerChoice === 'rock') {
return 'The user won';
} else {
return 'The computer won';
}
} else if (userChoice === 'Scissors') {
if (computerChoice === 'Paper') {
return 'The user won';
} else {
return 'The computer won';
}
}
}
console.log(determineWiner('rock', 'paper'));
console.log(determineWiner('paper', 'rock'));
console.log(determineWiner('scissors', 'paper'));
const playGame = () => {
const userChoice =
getUserChoice('scissors');
const computerChoice =
getComputerChoice();
console.log(`you threw: ${userChoice}`);
console.log(`The computer threw: ${computerChoice}`);
console.log(determineWinner(userChoice, computerChoice));
};
playgame();

Javascript not running - no error message

I've set up this rock, paper scissors game. However, the Javascript is not running and I'm not receiving any errors. Any suggestions?
function play(humanScore) {
var computerScore = getcomputerScore();
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
human++
} else if (computerScore == "paper") {
computer++
}
} else if (humanScore == "scissors") {
if (computerScore == "scissors") {
} else if (computerScore == "paper") {
human++
} else if (computerScore == "rock") {
computer++
}
} else if (humanScore == "paper") {
if (computerScore == "paper") {
} else if (computerScore == "scissors") {
computer++
} else if (computerScore == "rock") {
human++
}
}
}
function getcomputerScore() {
var randomplay = ["rock", "paper", "scissors"];
var play = randomplay[Math.floor(Math.random() * myArray.length)];
return play
}
This is the code setting up humanScore:
var human = 0;
var computer = 0;
document.getElementById("rock").onClick = pickRock;
document.getElementById("scissors").onClick = pickScissors;
document.getElementById("paper").onClick = pickPaper;
function pickRock() {
play("rock");
}
function pickScissors() {
play("scissors");
}
function pickPaper() {
play("paper");
}
The name of the property is onclick, not onClick; note the lowercase c.
There’s at least one other error (myArray.length, as #RobG points out), but this will make them actually throw.
Probably better suited to a code review section, but here goes…
function play(humanScore) {
var computerScore = getcomputerScore();
variables humanScore and computerScore aren't actually scores, they are symbols the players have chosen to play, so the variables might be better as humanChoice and computerChoice. This also means that the globals human and computer can be better named as humanScore and computerScore.
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
Rather than leaving a blank block, better to either insert a comment to say "no adjustment". Better to test equivalent choices up front, then you're left with binary choices, so you can do something like:
var humanScore = 0;
var computerScore = 0;
function play(humanChoice) {
// IE tends to play with capitalisation of values
humanChoice = humanChoice.toLowerCase();
var computerChoice = getComputerChoice();
// If same choice, no change of score
if (computerChoice == humanChoice) {
return;
}
// Only binary win/lose choices left
if (humanChoice == 'rock') {
computerChoice == 'paper'? ++computerScore : ++humanScore;
} else if (humanChoice == 'paper') {
computerChoice == 'scissors'? ++computerScore : ++humanScore;
} else if (humanChoice == 'scissors') {
computerChoice == 'rock'? ++computerScore : ++humanScore;
}
}
There was an error in this function too:
function getComputerChoice() {
var choices = ['rock','paper','scissors'];
return choices[Math.random()*choices.length | 0];
}
Lastly, make sure the buttons are in the page before adding the listener, and make sure the property names have the correct case (it doesn't matter for HTML attributes, but it does for javascript property names):
window.onload = function() {
document.getElementById("rock").onclick = pickRock;
document.getElementById("scissors").onclick = pickScissors;
document.getElementById("paper").onclick = pickPaper;
}

Categories

Resources