# Function to alternate players' turns, unless a player has won

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)?

• 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. – 200_success Jul 11 '17 at 13:59

"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";
}

• 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. – Gerrit0 Jul 12 '17 at 2:10

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";
}

• Yup, this was my first thought when I saw the question. I find this so much clearer than using XOR here. – Simon Forsberg Jul 11 '17 at 14:02