【问题标题】:Creating _.reduce from scratch从头开始创建 _.reduce
【发布时间】:2021-11-18 16:48:14
【问题描述】:

我正在尝试从头开始从下划线库重新创建 _.reduce 方法,但三个测试用例都失败了。 1. 即使迭代器返回未定义,也应该继续调用迭代器。 2. 如果传入备忘录,则应将数组的每个项目传递给迭代器。 3. 如果未传入备忘录,则应首先将数组的第二项传递给迭代器。我一直在查看文档和我认为 iterator(accumulator, collection[1], 1, collection) 会涵盖第三种情况,但我想不会。

_.reduce = function(collection, iterator, accumulator) {
    // TIP: To support both arrays and objects, try re-using each() here
    if (accumulator === undefined) {
      accumulator = collection[0];
      iterator(accumulator, collection[1]);
    }

    _.each(collection, function(val) {
      iterator(accumulator, val);
    }
    );
    return accumulator;
  };

【问题讨论】:

  • 你不存储iterator(...)的结果
  • 其实你的功能和underscorejs.org/#reduce(1.13.1)一点都不相似,你想实现什么?
  • 好吧,我的测试用例似乎不同意,我已经通过了 7/10 次测试@appleapple
  • @ Ronny Fitzgerald,与 underscore.js 没有任何相似之处,并且您通过的(未知)测试是无关的。另外,您应该让问题包含minimal reproducible example。
  • 为什么不相似?请不要只说负面的话来贬低别人。我的测试用例表明我走在正确的轨道上,所以我认为它们不相关

标签: javascript underscore.js


【解决方案1】:

一些问题:

  • 如果accumulator 未定义,您的代码首先使用collection[1] 调用iterator,但如果collection 不是数组,则它不会代表集合的第二个元素。例如,{a:1, b:2} 中的第二个元素是 collection.b。

  • 如果 accumulator 未定义,您的代码仍将继续执行 _.each,这将在集合的第一个元素上调用 iterator,这是您想要避免的...

  • 您的代码忽略了调用iterator 返回的值。它应该捕获这个返回值并将其分配给accumulator

  • iterator 应该使用第三个参数调用:值的索引/键。

  • 应该使用第四个参数调用iterator:正在迭代的完整集合

更正:

_.reduce = function(collection, iterator, accumulator) {
    _.each(collection, function(val, i) {
        if (accumulator === undefined && i === 0) accumulator = val;
        else accumulator = iterator(accumulator, val, i, collection);
    });
    return accumulator;
};

// Tests
console.log(_.reduce([1,2,3], (a, b) => a+b, 1) === 7);
console.log(_.reduce([1,2,3], (a, b) => a+b) === 6);
console.log(_.reduce({a: 1, b: 2, c:3}, (a, b, i) => a+b, 0) === 6);
console.log(_.reduce({a: 1, b: 2, c:3}, (a, b, i) => a+i, "") === "abc");
console.log(_.reduce([], (a, b) => a+b, 0) === 0);
console.log(_.reduce([], (a, b) => a+b) === undefined);
console.log(_.reduce([1,2,3], (a, b, i, all) => a + b * all[i-1]
) === 9);
<script src="https://cdn.jsdelivr.net/npm/underscore@1.13.1/underscore-umd.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2021-04-12
    • 2011-05-03
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多