javascript - 如何避免重复相同的功能并使其在 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 响应的值。
解决方案
好吧,如果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');
}
}
推荐阅读
- c# - 如何向 HttpClient() 添加自定义标头?
- c# - 为什么 C# 的 TrimEnd() 函数的行为如下?
- apache-flink - 从 Flink 中的 WebMonitorEndpoint (Rest Monitoring API) 获取自定义计量指标
- c# - 跟踪用户/组的更改
- javascript - 将 Firestore 数据添加到 DataTable
- linux - 在虚拟机中与 docker 中的 kafka 连接
- javascript - 如何在javascript中获取带有主题标签符号的当前网址?
- html - 如何设置高度
- linux - 用于停止 tomcat 的 shell 脚本
- javascript - disableOpenGesture 隐藏不起作用导航抽屉反应本机