是否可以通过编程方式更改js中条件语句的逻辑运算符?

时间:2019-02-28 14:52:35

标签: javascript optimization

我有两个几乎相同的功能,除了一个不同之处是if中的逻辑运算符。

我无法写<=,因为我需要在整个数组中搜索相等的斑点,并且只有在找不到的情况下才搜索<斑点。

// === in if
for (let i = 0; i < res.potentialFreeSpots.length; i++) {
  let freeSpotLength = Math.round(
    Math.abs(res.potentialFreeSpots[i]["end"] - res.potentialFreeSpots[i]["start"]) / 60000
  );
  if (credentials.serviceTimeConsumption === freeSpotLength) {
    return formFreeSpot(res.potentialFreeSpots[i]["start"], res.excludedTimes);
  }
}

// < in if
for (let i = 0; i < res.potentialFreeSpots.length; i++) {
  let freeSpotLength = Math.round(
    Math.abs(res.potentialFreeSpots[i]["end"] - res.potentialFreeSpots[i]["start"]) / 60000
  );
  if (credentials.serviceTimeConsumption < freeSpotLength) {
    return formFreeSpot(res.potentialFreeSpots[i]["start"], res.excludedTimes);
  }
}

2 个答案:

答案 0 :(得分:4)

只需执行功能即可。进行最小程度的修改以使其起作用:

function something(compare){
    for (let i = 0; i < res.potentialFreeSpots.length; i++) {
      let freeSpotLength = Math.round(
        Math.abs(res.potentialFreeSpots[i]["end"] - res.potentialFreeSpots[i]["start"]) / 60000
      );
      if ( compare(credentials.serviceTimeConsumption, reeSpotLength)) {
        return formFreeSpot(res.potentialFreeSpots[i]["start"], res.excludedTimes);
      }
    }
}

现在称呼它

something( (a,b) => a === b )

something( (a,b) => a < b )

答案 1 :(得分:0)

因此,此代码完全需要一些改进。让我们根据@farvilain的响应进行正确处理。

据我所见,res.potentialFreeSpots是一个集合。基于此,我们可以使用诸如forEach,map,一些,find等的收集方法。

const doSomething = comparator => {
   if (!res. potentialFreeSpots) {
     return false;
   }

   const freeSpot = res.potentialFreeSpots
     .find(freeSpot => {
        const freeSpotLength = Math.round(Math.abs(freeSpot['end'] - freeSpot['start']) / 60000);

        return comparator(freeSpotLength, credentials.serviceTimeConsumption);
     });

   return formFreeSpot(freeSpot['start'], res.excludedTimes);
}

其中的比较器是一个函数,因此您可以像@farvilain示例中一样调用它

doSomething((a, b) => a === b));
doSomething((a, b) => a < b));

这种解决问题的方法使其更具可读性,并且更易于测试。