javascript - map()、reduce() 和 filter 与 forEach()

标签 javascript performance functional-programming mapreduce

刚学了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/

相关文章:

java - 您使用函数式 Java 项目有哪些经验?

class - 类如何帮助您管理大型应用程序?

javascript - 如何在不使用验证码验证器的情况下实现Firebase电话验证系统?

javascript - 如何检查以确保我的所有输入都是 :radio elements have a value?

python - 在 Python 中查找数字的所有因数的最有效方法是什么?

javascript - 打印数组内某些对象日期范围内包含的所有日期的最佳方法是什么?

javascript - 如何在打开新窗口后聚焦主网页?

javascript - Jasmine 测试: Spying on the first call to a function

optimization - 这些天什么时候使用定点

Python "Memory Error."/节省内存