Home > other >  Javascript ,simplifying a method
Javascript ,simplifying a method

Time:09-23

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.

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

this an XOR Logic

if (((userColor==='white')?1:0)^((length%2===0)?1:0))
  {
  max   = black = time - timeA;
  white = time - timeB;
  }
else
  {
  max   = white = time - timeA;
  black = time - timeB;
  }
  • Related