刚学了MapReduce,想问问写有没有优势
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;
最佳答案
对于 future 的读者,还有一些更惯用的方式来以函数方式编写归约。
通常使用这些是因为它们更清晰地传达了意图(并且不向范围添加变量)。
注意:我假设 this.items
有类型
({ quantity: number; price: number } | undefined)[] | undefined
但是每个示例都比问题中的两个示例可以容忍更多的无效数据。减少前的过滤和映射
最后的默认值
return this.items
?.filter(item => item?.quantity && item.price)
.map(item => item.quantity * item.price)
.reduce((a, b) => a + b, 0) ?? 0
开头的默认数组return (this.items ?? [])
.filter(item => item?.quantity && item.price)
.map(item => item.quantity * item.price)
.reduce((a, b) => a + b, 0)
处理 map 中的过滤器我不会因为前两个更清楚地传达意图而推荐这些。
最后的默认值
return this.items
?.map(item => (item?.quantity ?? 0) * (item?.price ?? 0))
.reduce((a, b) => a + b, 0) ?? 0
开头的默认数组return (this.items ?? [])
.map(item => (item?.quantity ?? 0) * (item?.price ?? 0))
.reduce((a, b) => a + b, 0)
解构前面的每个例子都可以用解构来代替。
我包括一个例子。
return (this.items ?? [])
.filter(item => item) // Ensure item exists; sufficient for the cases we need to worry about
.map(({ price = 0, quantity = 0 }) => quantity * price)
.reduce((a, b) => a + b, 0)
没有 map 我们现在可以在没有 map 的情况下进行缩减。
这也可以在不解构的情况下完成,但这似乎(对我来说)不优雅。
return (this.items ?? [])
.filter(item => item)
.reduce((sum, { price = 0, quantity = 0 }) => sum + quantity * price, 0)
当然,您可以更改过滤条件,这使我们大致回到问题中的第一个示例:return (this.items ?? [])
.filter(item => item?.price && item.quantity)
.reduce((sum, { price, quantity }) => sum + quantity * price, 0)
原创 forEach
环形也可以对原始循环进行其中一些更改:
let total = 0;
items?.forEach((item) => {
if (item?.quantity && item.price) {
total += item.quantity * item.price;
}
});
return total;
关于javascript - map()、reduce() 和 filter 与 forEach(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836751/