Darkened
Darkened

Reputation: 47

Function using switch not returning the desired value

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

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36584

Following are mistakes of your code.

  • You can't have two variables for switch statement. 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:

  • Create an object with keys as return values 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']
  • You Object.entries on the object. And use find() on entries.
  • Inside find() put the values ch1 and ch2 in array in both order i.e [ch1,ch2] and [ch2,ch1]
  • Check if any of the array is equal to any of value of object using every()
  • If yes then return the key otherwise return '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

Related Questions