This is an ongoing school project that I would like to improve. The point is to make the code as efficient (or short) as possible. I would like to reduce it by finding an al
You can also use an array to check the winner. Order the array so that the winner is always on the right side. Then compare if the machine's choise is the one next to user's choise, like so:
var weapons = ['paper', 'scissors', 'rock'],
user = 'scissors',
machine = 'paper',
uIdx = weapons.indexOf(user),
mIdx = weapons.indexOf(machine),
winner;
if (uIdx !== mIdx) {
winner = (mIdx === (uIdx + 1) % 3) ? 'machine' : 'user';
} else {
winner = 'tie';
}
console.log(winner);
A fiddle to play with.
The modulo operator makes the magic at the end of the array. If user has chosen "rock", the next to it would be undefined, but the modulo operator of 3 % 3 returns 0, hence "paper" is compared to "rock".