2
我刚才了解了MapReduce的,所以我不知道是否有书面的MapReduce在JavaScript
const initialValue = 0;
if (this.items) {
return this.items.filter(function (item) {
return item && item.quantity && item.price;
}).reduce(function(previousValue, currentValue) {
return previousValue + currentValue.quantity * currentValue.price ;
}, initialValue);
} else {
return initialValue;
}
,而不是仅仅
let total = 0;
if (this.items) {
this.items.forEach(function(item) {
if (item && item.quantity && item.price) {
total += item.quantity * item.price;
}
});
}
return total;
首先可以肯定的是慢。你也可以使用for循环使第二个更快 – CoderPi
如果你使用MapReduce只是为了累积值(以迭代方式),那么第一个和第二个没有什么优势。不过别忘了,MapReduce背后的想法是用于并行计算(分布式系统/集群)。所以如果'forEach'没有被设计出来,实现并行运行,那么它不适合分布式环境,第二种解决方案不适用于并行计算,因此这两种解决方案是完全不同的。 – pasty