javascript - 如何降低 if/else 复杂度?

标签 javascript jquery if-statement cyclomatic-complexity

我嵌套了一些 if/else 语句,但我想减少它们的开销。

在示例中,我正在评估从哪个下拉列表中单击了 li 项目,以及该 li 项目是否是第一个 (currentIndex === 0)。

代码:

if (parentIndex === 1) {
  // But its own index is 0
  if (currentIndex === 0) {
    parentIndex = 2;
    updatedIndexPos = array[1];
    mainIndex =list_2.indexOf(updatedIndexPos);
    // If the previous line is -1:
    if (mainIndex === -1) {
      parentIndex = 1;
      updatedIndexPos = filterIndexPos;
      mainIndex = list_1.indexOf(updatedIndexPos);
    }
  } else {
    mainIndex = list_1.indexOf(mainIndexPos);
  }
} else if (parentIndex === 2) {
  // But its own index is 0
  if (currentIndex === 0) {
    parentIndex = 1;
    updatedIndexPos = array[0];
    mainIndex = list_1.indexOf(updatedIndexPos);
    // If the previous line is -1:
    if (mainIndex === -1) {
      parentIndex = 2;
      updatedIndexPos = filterIndexPos;
      mainIndex = list_2.indexOf(updatedIndexPos);
    }
  } else {
    mainIndex = list_2.indexOf(mainIndexPos);
  }
}

看看它有很多重用的代码,eslint 给我的复杂度是 7。我尝试将其分解为更小的函数并传递参数,但仍然无法解决此代码块的复杂性。

最佳答案

将逻辑建模为 state-machine 通常很有帮助。 因此,您已经定义了状态以及它们之间的转换。

var action = 'foo';
var actionParams = {...};
var currentState = getState({parentIndex: parentIndex, ...});
if (currentState.canPerform(action)) {
  currentState.perform(action, actionParams);
}

关于javascript - 如何降低 if/else 复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50155286/

相关文章:

javascript - 如何在按下 F5 或刷新按钮时仅刷新页面的一部分

javascript - nodejs 一致性哈希库

php - 如何在单独的页面上显示每个(只有一个)搜索结果 mysql php

javascript - Android:无法捕获 JavaScript 中的后退按钮点击

javascript - Javascript 中使用的 JQuery MarginRight 和 CSS margin-right 有什么区别?

javascript - JS 条件语句不起作用

javascript - React Native fetch api 在转换为 json 之前检查 http 状态

javascript - 让用户输入以 "BR"或 "BT"开头

ruby - 在 Ruby 中编写此条件的更短方法 n != 1 && n != 2 && n != 3 && n !=4

R: dplyr 管道条件超前/滞后使用 ifelse 具有意外行为