Reputation: 47
I'm new to JS, and I've having some trouble with this particular code. It is supposed to be a Rock, Paper, Scissors using the switch statement, but it's not returning the draw value and is returning other values wrong:
function RPS(ch1, ch2){
switch (ch1, ch2){
case ('r' && 'p') || ('p' && 'r'):
return 'p';
break;
case ('r' && 's') || ('s' && 'r'):
return 'r';
break;
case ('p' && 's') || ('s' && 'p'):
return 's';
break;
default:
return 'draw';
}
}
console.log(RPS('s', 's'));
So testing with 's' and 's', I was expecting 'draw' but it returned 'r'. What did I do wrong?
Upvotes: 2
Views: 48
Reputation: 36584
Following are mistakes of your code.
ch1, ch2
will evaluate to ch2
.'r' && 'p'
will always evaluate to true
. Because both r
and p
are truthy values.You can do that in following steps:
p,q,r
. And their values will be the array of two values for which you want to checking in the original code. For example p
will have array ['r','p']
Object.entries
on the object. And use find()
on entries.find()
put the values ch1
and ch2
in array in both order i.e [ch1,ch2]
and [ch2,ch1]
every()
'draw'
function RPS(ch1, ch2){
const obj = {
p:['r','p'],
r:['r','s'],
q:['p','s']
}
let entry = Object.entries(obj)
.find(([k,v]) =>
[ch1,ch2].every((x,i) => x === v[i]) ||
[ch2,ch1].every((x,i) => x === v[i])
)
return entry ? entry[0] : 'draw';
}
console.log(RPS('s','p'))
Upvotes: 2