2016-01-17 23 views
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; 
+0

首先可以肯定的是慢。你也可以使用for循环使第二个更快 – CoderPi

+0

如果你使用MapReduce只是为了累积值(以迭代方式),那么第一个和第二个没有什么优势。不过别忘了,MapReduce背后的想法是用于并行计算(分布式系统/集群)。所以如果'forEach'没有被设计出来,实现并行运行,那么它不适合分布式环境,第二种解决方案不适用于并行计算,因此这两种解决方案是完全不同的。 – pasty

回答

0

我看不到任何优势第一的任何好处在第二*。然而,第二个更快,然后看起来更干净!第一个目的可能是演示如何使用内置的数组函数。

但是,mapreduce用于很多元素,所以你可以尽可能地加快速度。这应该是你可以得到最快的:

const initialValue = 0; 
let total = initialValue; 
if (this.items) { 
    for (var i = this.items.length; i--;) { 
    let item = this.items[i] 
    if (item && item.quantity && item.price) { 
     total += item.quantity * item.price; 
    } 
    } 
    return total; 
} else { 
    return initialValue 
} 

在addtion你可以放下if内循环,如果你知道你的阵列是consitant。这两个if都只是为了确保数组已正确构建并且脚本不会运行到错误中,这对于用户数据输入将非常有用,但在封闭的系统中,您不需要它们。


* 我注意到,二是缺少默认值return initialValue