const compareGuesses = (humanGuess, computerGuess, secretNumber) => { let humanGuessDifference = secretNumber - humanGuess let computerGuessDifference = secretNumber - computerGuess if (computerGuessDifference > humanGuessDifference) { var humanWinner = true } else { var humanWinner = false } return humanWinner }; console.log(compareGuesses(1, 10, 2))
Advertisement
Answer
It doesn’t.
const compareGuesses = (humanGuess, computerGuess, secretNumber) => { const humanGuessDifference = secretNumber - humanGuess const computerGuessDifference = secretNumber - computerGuess if (computerGuessDifference > humanGuessDifference) { return true; } else { return false; } }; console.log(compareGuesses(10, 1, 2))
But to properly compare the difference, you should keep in mind that subtraction may result in a negative number – in which case you may get something like if (1 > -8)
– the magnitude of the difference is larger, but if it’s negative, it’ll still fulfill the >
. Use Math.abs
to take the absolute value of the differences.
const compareGuesses = (humanGuess, computerGuess, secretNumber) => { const humanGuessDifference = secretNumber - humanGuess const computerGuessDifference = secretNumber - computerGuess return Math.abs(humanGuessDifference) < Math.abs(computerGuessDifference); }; console.log('first is closer:', compareGuesses(10, 1, 2)) console.log('first is closer:', compareGuesses(1, 10, 2))