2
\$\begingroup\$

I am doing a coding challenge and it basically says this. There are two players, "black" and "white" and they take turns at a game. If a player won the last turn then it is his turn again, otherwise it is the other player's turn. The whole challenge is here.

Here is the original code I used for that:

function whoseMove(lastPlayer, win) {
  if (lastPlayer == "white") {
      if (win) {
          return "white";
      }
      return "black";
  } else {
      if (win) {
          return "black";
      }
      return "white";
  }
}

however I realised that this could be simplified by changing it to this:

function whoseMove(lastPlayer, win) {
  if (lastPlayer == "white") {
      return win ? "white" : "black";
  } else {
      return win ? "black" : "white";
  }
}

I wonder if this could be simplified even more? Is it possible to have more than one condition in the conditional return statement (I think that is what it is called)?

\$\endgroup\$
1
  • \$\begingroup\$ Please also show us the code that calls this function. I suspect that you would be better off putting the conditional elsewhere in your code, instead of in this function that appears to give the winning player an extra turn. \$\endgroup\$ – 200_success Jul 11 '17 at 13:59
-1
\$\begingroup\$

"White" is returned when both conditions are true or when both are false so you can use XOR, denoted as ^ in JavaScript.

function whoseMove(lastPlayer, win) {
  return lastPlayer == "white" ^ !!win ? "black" : "white";
}

I would advise against it since that's less obvious. Here's a self-explanatory condition:

function whoseMove(lastPlayer, win) {
  return lastPlayer == "white" && win || lastPlayer != "white" && !win ? "white" : "black";
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Personally, I would much prefer the OP's original code to either of these solutions. There is way too much happening on a single line even in your second function here. \$\endgroup\$ – Gerrit0 Jul 12 '17 at 2:10
3
\$\begingroup\$

You could return the same player if win is true, otherwise return the other player, this is done with only 2 tests:

function whoseMove(lastPlayer, win) {
    if (win) return lastPlayer;
    return lastPlayer == "black" ? "white" : "black";
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Yup, this was my first thought when I saw the question. I find this so much clearer than using XOR here. \$\endgroup\$ – Simon Forsberg Jul 11 '17 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy