Rock, Paper, Scissors / Function Writing Variety

const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if(userInput === 'rock' || userInput === 'scissors' || userInput === 'paper') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

const getComputerChoice = () => {
  randomNumber = Math.floor(Math.random() * 3);
  switch(randomNumber) {
    case 0:
    return 'rock';
    break;
    case 1:
    return 'scissors';
    break;
    case 2:
    return 'paper';
    break;
  }
}

const determineWinner = (userChoice, computerChoice) => {
  if(userChoice === computerChoice) {
    return 'Game is tied!';
  } else if(userChoice === 'rock' && computerChoice === 'scissors') {
    return 'User wins!';
  } else if(userChoice === 'scissors' && computerChoice === 'rock') {
    return 'Computer wins!';
  } else if(userChoice === 'scissors' && computerChoice === 'paper') {
    return 'User wins!';
  } else if(userChoice === 'paper' && computerChoice === 'scissors') {
    return 'Computer wins!';
  } else if(userChoice === 'paper' && computerChoice === 'rock') {
    return 'User wins!';
  } else if(userChoice === 'rock' && computerChoice === 'paper') {
    return 'Computer wins!';
  }
}

function playGame() {
  let userChoice = getUserChoice('paper');
  console.log(userChoice);
  let computerChoice = getComputerChoice('paper');
  console.log(computerChoice);
  console.log(determineWinner(userChoice, computerChoice))
}

playGame();

Is it okay to write determineWinner function this way:

const determineWinner = (userChoice, computerChoice) => {
  if(userChoice === computerChoice) {
    return 'Game is tied!';
  } else if(userChoice === 'rock' && computerChoice === 'scissors') {
    return 'User wins!';
  } else if(userChoice === 'scissors' && computerChoice === 'rock') {
    return 'Computer wins!';
  } else if(userChoice === 'scissors' && computerChoice === 'paper') {
    return 'User wins!';
  } else if(userChoice === 'paper' && computerChoice === 'scissors') {
    return 'Computer wins!';
  } else if(userChoice === 'paper' && computerChoice === 'rock') {
    return 'User wins!';
  } else if(userChoice === 'rock' && computerChoice === 'paper') {
    return 'Computer wins!';
  }
}

The guy in the video wrote it in a different way, but mine does the same thing…

Thank you!

Hi,
if it works it is fine to write it that way. But I would say that it is not ideal because it is a bit confusing and therefore difficult to maintain.
It is always useful to bear in mind that things could change, e.g. a new item – like a well – could be introduced to the game. Then the code that could be adjusted the fastest possible way would be best (along with the fastest runtime, but that does not make much of a difference at this stage).

1 Like

Thank you for the response!

1 Like