【问题标题】:Javascript ,simplifying a methodJavascript,简化方法
【发布时间】:2021-09-23 00:37:22
【问题描述】:

我正在编写一个用于国际象棋的实用应用程序,并且我有一些重复的代码模式,在不同的方法中不断重复。

基本上,我正在跟踪用户{white, black} 的颜色。如果用户是white,那么他们的动作遵循moves[i] % 2 ==0 的模式(因为总是由白人玩家开始游戏)。

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

这是我使用上述玩家颜色模式的一个示例。有没有人看到我可以优雅地减少这段代码的方法?

如何简化这段 sn-p 代码?一定有办法,因为这里有对称模式

我尝试过的事情

我已经尝试编写一个方法来接收用户的color 以及max whiteblack,但我似乎总是回到我编写的相同代码,没有进展。

【问题讨论】:

    标签: javascript simplify simplification


    【解决方案1】:

    我宁愿从whiteblack 生成一个数组,而不是独立变量 - 然后您可以计算目标索引,适当分配,并对1 - index 元素执行相同操作。

    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;
    

    newMaxColorWhite 变量不是必要的 - 您可以完全省略它并使用条件运算符在一行中定义索引 - 但我认为它使代码的意图更清晰。

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

    你也可以替换

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

    userIsWhite === evenTurn
    

    但这可能不是那么容易理解的。

    【讨论】:

      【解决方案2】:

      您可以使用三元运算符并完全删除嵌套的 if/else 语句:

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

      【讨论】:

        【解决方案3】:

        这是一个异或逻辑

        if ((userColor !== 'white') ^ (length % 2))
          {
          max   = black = time - timeA;
          white = time - timeB;
          }
        else
          {
          max   = white = time - timeA;
          black = time - timeB;
          }
        

        【讨论】:

          猜你喜欢
          • 2018-06-12
          • 2011-06-08
          • 2021-11-21
          • 1970-01-01
          • 1970-01-01
          • 2019-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多