首页 > 解决方案 > 如何避免重复相同的功能并使其在 Javascript 中通用

问题描述

尝试将以下片段重构为重复超过 1 次的相同功能。

有人可以告诉我如何使它通用吗?

由于它的重复,我无法获得代码覆盖率。

method_a {
let category = [];
category.forEach(d => {
    if(d.includes("prop1","prop2")) {
        // something...
        this.otherMethod('string1');
    }
    if(d === "prop3") {
        this.otherMethod('string2');
    }
});
}


method_b {
// api response
data[0].category.forEach(d => {
    if(d.includes("prop1","prop2")) {
        this.otherMethod('string1');
    }
    if(d === "prop3") {
        this.otherMethod('string2');
    }
});
}

这里令人困惑的是method_a有一个局部变量作为一个空数组并且method_b具有来自 JSON 响应的值。

标签: javascriptecmascript-6

解决方案


好吧,如果forEach在这两种情况下该方法必须做的事情完全相同,您可以为它创建一个单独的方法。

category.forEach(loopAction);
data[0].category.forEach(loopAction);

function loopAction(d) {
    if(d.includes("prop1","prop2")) {
        this.otherMethod('string1');
    }
    if(d === "prop3") {
        this.otherMethod('string2');
    }
}

推荐阅读