【发布时间】: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。
-
为什么不相似?请不要只说负面的话来贬低别人。我的测试用例表明我走在正确的轨道上,所以我认为它们不相关