Description
- You have to return which player won.
- In case of a draw return ‘Draw!’.
Solution 01
function rockPaperScissors(p1, p2) {
if (p1 === 'rock' && p2 === 'rock') return 'Draw!';
if (p1 === 'rock' && p2 === 'paper') return 'Player 2 won!';
if (p1 === 'rock' && p2 === 'scissors') return 'Player 1 won!';
if (p1 === 'paper' && p2 === 'rock') return 'Player 1 won!';
if (p1 === 'paper' && p2 === 'paper') return 'Draw!';
if (p1 === 'paper' && p2 === 'scissors') return 'Player 2 won!';
if (p1 === 'scissors' && p2 === 'rock') return 'Player 2 won!';
if (p1 === 'scissors' && p2 === 'paper') return 'Player 1 won!';
if (p1 === 'scissors' && p2 === 'scissors') return 'Draw!';
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('rock', 'paper'); // Player 2 won!
rockPaperScissors('rock', 'scissors'); // Player 1 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
Solution 02
function rockPaperScissors(p1, p2) {
if (p1 === p2) return 'Draw!';
if (p1 === 'rock' && p2 === 'paper') return 'Player 2 won!';
else if (p1 === 'paper' && p2 === 'scissors') return 'Player 2 won!';
else if (p1 === 'scissors' && p2 === 'rock') return 'Player 2 won!';
else return 'Player 1 won!';
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('rock', 'paper'); // Player 2 won!
rockPaperScissors('rock', 'scissors'); // Player 1 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
Solution 03
function rockPaperScissors(p1, p2) {
if (p1 === p2) return 'Draw!';
const obj = {
rock: 'scissors',
paper: 'rock',
scissors: 'paper'
};
if (p1 === obj[p2]) {
return 'Player 2 won!';
} else {
return 'Player 1 won!';
}
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('rock', 'paper'); // Player 2 won!
rockPaperScissors('rock', 'scissors'); // Player 1 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
Solution 04
function rockPaperScissors(p1, p2) {
const obj = {
rock: 'scissors',
paper: 'rock',
scissors: 'paper'
};
if (p1 === p2) {
return 'Draw!';
} else {
return 'Player ' + (p1 === obj[p2] ? 2 : 1) + ' won!';
}
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('rock', 'paper'); // Player 2 won!
rockPaperScissors('rock', 'scissors'); // Player 1 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!
Solution 05
function rockPaperScissors(p1, p2) {
if (p1 === p2) return 'Draw!';
return `Player ${/rockscissors|paperrock|scissorspaper/.test(p1 + p2) ? 1 : 2} won!`;
}
rockPaperScissors('rock', 'rock'); // Draw!
rockPaperScissors('rock', 'paper'); // Player 2 won!
rockPaperScissors('rock', 'scissors'); // Player 1 won!
rockPaperScissors('paper', 'rock'); // Player 1 won!