0

I am coding a utility app for chess and I have some repetitive code pattern that keeps repeating across different methods.

Basically, I am tracking the color of the user {white, black}. If the user is white then the moves they do follow the pattern moves[i] % 2 ==0 (since a white player always starts the game).

if (userColor === "white") {
    if(length % 2 === 0) {
      max = white = time - timeA;
      black = time - timeB;
    } else {
      max= black = time - timeA;
      white = time - timeB;
    }
  } else {
    if(length % 2 === 0) {
      max = black = time - timeA;
      white = time - timeB;
    } else {
      max = white = time - timeA;
      black = time - timeB;
    }
  }

This is one example where I use the pattern for player color mentioned above. Does anyone see a way where I could elegantly reduce this code?

How could I simplify this snippet of code? There must be a way since there is a symmetry pattern here

Things I have tried

I have tried writing a method that takes in the color of the user along with max white and black, but I always seem to go back to the same code that I have written, doing no progress.

hexaquark
  • 883
  • 4
  • 16

3 Answers3

1

You can use a ternary operator and remove the nested if/else statements altogether:

if (userColor === "white") {
    max = (length % 2 === 0 ? white : black) = time - timeA;
    black = time - timeB;
} else {
    max = (length % 2 === 0 ? black : white) = time - timeA;
    white = time - timeB;
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
1

I'd prefer to make an array from white and black instead, instead of standalone variables - then you can calculate the target index, assign appropriately, and do the same for the 1 - index element too.

const colors = [white, black];
// always use `colors` now instead of white and black
// and make userColor into userColorIndex - an index of 0 for white, 1 for black - or use a boolean `userIsWhite`
const evenTurn = length % 2;
const newMaxColorWhite = userIsWhite && evenTurn || !userIsWhite && !evenTurn;
const index = newMaxColorWhite ? 0 : 1;
max = colors[index] = time - timeA;
colors[1 - index] = time - timeB;

The newMaxColorWhite variable isn't necessary - you could omit it entirely and define the index in a single line with the conditional operator - but I think it makes the intent of the code clearer.

const index = userIsWhite && evenTurn || !userIsWhite && !evenTurn ? 0 : 1;
max = colors[index] = time - timeA;
colors[1 - index] = time - timeB;

You could also replace

userIsWhite && evenTurn || !userIsWhite && !evenTurn

with

userIsWhite === evenTurn

but that might not be all that understandable.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

this an XOR Logic

if ((userColor !== 'white') ^ (length % 2))
  {
  max   = black = time - timeA;
  white = time - timeB;
  }
else
  {
  max   = white = time - timeA;
  black = time - timeB;
  }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40