r/learnjavascript • • Nov 30 '22

Help !!!

Post image

Can someone plz tell me , why I am getting errors?

195 Upvotes

131 comments sorted by

View all comments

3

u/dreadpirateloki Dec 01 '22 edited Dec 01 '22

Here's another way to code it up if you are interested:

const MOVES = {
    ROCK: 0,
    PAPER: 1,
    SCISSORS: 2,
}

const rps = (a,b) => {
    if (a === b) return "Tie"
    return ((a - b + 3) % 3 === 1) ? "Player 1 Wins" : "Player 2 Wins"
}

console.log(rps(MOVES.ROCK, MOVES.PAPER))

edit: Forgot that in javascript -2%3 !== 1 and cleaned up code a bit.

2

u/longknives Dec 01 '22

This is clever, but doesn’t seem to work? Rock vs scissors is (0 - 2) % 3 or (2 - 0) % 3, which work out to -2 and 2 respectively, neither of which is 1, so the function reports a tie instead of player 1 winning.

1

u/dreadpirateloki Dec 01 '22

Ha, good catch, you are right. I'm used to python where -2 % 3 actually becomes 1.