【问题标题】:Node JS: Code Refactor with almost similar codes in different forEachNode JS:代码重构,在不同的 forEach 中具有几乎相似的代码
【发布时间】:2017-11-01 07:43:53
【问题描述】:

说,我有一些代码如下所示:-

objects1.forEach(function check(o1) {
    if (o1.name === object.name) {
        object.name = object.name + objectType;
    }
});

objects2.forEach(function ifNameMatch(o2) {
    if (o2.name === object.name) {
        object.name = object.name + objectType;
    }
});

有什么办法可以将这 2 个 forEach 替换为一个或以更好的方式编写吗?

您可以提供任何建议。

【问题讨论】:

  • 您在寻找 ES5 还是 ES6 的答案?

标签: node.js refactoring


【解决方案1】:

首先我会为每个我必须做的对象创建一个生成器,如果它是一个重复的过程,那么我会返回一个处理集合的函数,在你的场景中是 objects1objects2

let nameMatchGenerator = (object, objectType)  => {
return (collections) => { 
  return collections.forEach(collection) => {
    collection.forEach(o => {
      if (o.name === object.name) {
        object.name = object.name + objectType;
      }
    })
  }
}
let nameMatch = (object, objectType);
nameMatch([objects1, objects2]) // you can use this function to repeat 
                             // the process for as many collections

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2019-02-13
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多