skip to Main Content
function getComputerChoice(randomLetterGen) {
  function randomLetterGen() {
    function randomNumGen() {
      return Math.floor(Math.random() * 3);
    }
    let word = "rps";
    return word.charAt(randomNumGen());
  }
  let cpuInput;
  if (randomLetterGen() == "r") {
    cpuInput = "rock";
  } else if (randomLetterGen() == "p") {
    cpuInput = "paper";
  } else if (randomLetterGen() == "s") {
    cpuInput = "scissors";
  }
  return cpuInput;
}
console.log(getComputerChoice());

2

Answers


  1. Each time you call randomLetterGen(), it generates a new random letter independently.
    So, when you call it multiple times within the if statement, you’re potentially getting different results each time, leading to the possibility of getting undefined when none of the conditions match.

    function getComputerChoice() {
        function randomLetterGen() {
            function randomNumGen() {
                return Math.floor(Math.random() * 3);
            }
            let word = "rps";
            return word.charAt(randomNumGen());
        }
    
        let cpuInput = randomLetterGen(); // Call randomLetterGen() once and store the result
    
        if (cpuInput === "r") {
            return "rock";
        } else if (cpuInput === "p") {
            return "paper";
        } else if (cpuInput === "s") {
            return "scissors";
        }
    }
    
    console.log(getComputerChoice());
    

    Also, you’re not seeing the undefined option when Math.random()*3 is less than 2, it’s because the randomLetterGen() function is likely returning either "r", "p", or "s", which means one of the if conditions will match and you’ll get a valid result.

    Login or Signup to reply.
  2. You should call randomLetterGen() only one time and store it into a variable

    const randomLetter = randomLetterGen()
    if(randomLetter == "r"){}
    else if(randomLetter == "p"){}
    else if(randomLetter == "s"){}
    

    also the getComputerChoice function expect to receive one parameter but you pass nothing into in. And the parameter name should not the same with the local variable randomLetterGen

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search