从头开始创建_.duce

2022-03-23 00:00:00 javascript underscore.js

我试图从头开始从下划线库重新创建_.duce方法,但我有三个测试用例失败。1.即使迭代器返回UNDEFINED,也应该继续调用迭代器。2.如果传入备忘录,则应将数组的每一项都传递到迭代器中。3.如果没有传入备忘录,应该首先将数组的第二项传递到迭代器中。我一直在查看文档,我以为迭代器(累加器,集合[1],1,集合)会涵盖第三种情况,但我猜不会。

_.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;
  };

解决方案

一些问题:

  • 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>

相关文章