Ad

Moves the actions into a nested object, where the first level is Player1's action and the second layer Player 2's action.

This makes the templating easier.

also added an "Invalid action!" error if either player makes an invalid move.

Code
Diff
  • function rps(player1, player2) {
      const actions = {
        rock: {
          paper: 2,
          scissors: 1,
          rock: 0,
        },
        paper: {
          paper: 0,
          scissors: 2,
          rock: 1,
        },
        scissors: {
          paper: 1,
          scissors: 0,
          rock: 2,
        },
      };
    
      const result = actions?.[player1]?.[player2];
    
      if (result === 0) return "Draw!";
      if (!result) throw "Invalid action!";
      return `Player ${result} won!`;
    }
    • function rps(player1, player2) {
    • return player1 == player2 ? 'Draw!' :
    • player1 == 'rock' && player2 == 'scissors' ||
    • player1 == 'scissors' && player2 == 'paper' ||
    • player1 == 'paper' && player2 == 'rock' ? 'Player 1 won!' : 'Player 2 won!';
    • }
    • const actions = {
    • rock: {
    • paper: 2,
    • scissors: 1,
    • rock: 0,
    • },
    • paper: {
    • paper: 0,
    • scissors: 2,
    • rock: 1,
    • },
    • scissors: {
    • paper: 1,
    • scissors: 0,
    • rock: 2,
    • },
    • };
    • const result = actions?.[player1]?.[player2];
    • if (result === 0) return "Draw!";
    • if (!result) throw "Invalid action!";
    • return `Player ${result} won!`;
    • }