JS - Multiple Outcome Comparisons HELP

One way to improve the algorithm for the game of Rock, Paper, Scissors is by using an array of winning combinations instead of a bunch of nested if statements.

Here's an example of how you could implement this using an array:

function playRound(playerHand, cpuHand) {

const winningCombinations = [['rock', 'scissors'], ['paper', 'rock'], ['scissors', 'paper']]; const playerIndex = winningCombinations.findIndex(combo => combo[0] === playerHand); const cpuIndex = winningCombinations.findIndex(combo => combo[0] === cpuHand);

if (playerIndex === cpuIndex) { return "It's a tie!"; } else if (winningCombinations[playerIndex][1] === cpuHand) { return "CPU Wins!"; } else { return "Player Wins!"; } }

In this version, we create an array winningCombinations that contains all the winning combinations. We then use the findIndex method to get the index of the player's and CPU's hands in the array. We can then use those indices to check if it's a tie or if one of the hands wins based on the winning combinations in the array.

This approach is more concise and easier to read than using nested if statements. It also makes it easier to add more options to the game in the future if desired.

Another improvement you could make is to use constants or enums for the hand options instead of hard-coding the string values throughout your code. This would help reduce the likelihood of typos and make it easier to modify the options later on.

/r/learnprogramming Thread