我嵌套了一些 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/