首页 > 解决方案 > Javascript 流库 - 实现

问题描述

java 流(或其他语言的任何其他函数库)非常好。

例如,您可以有 ( js sudo code)。

Stream.of([1, 2, 3]).filter(x => x > 2).map(x => x * 5).result(); // [15]

忽略语法或具体实现它只是一个例子。

现在我的问题是流程有点复杂。

例如,如果我需要像这样的每个步骤的不同数据:

Stream.of([1,2, 3])
  .map(x => x * 3)
  .zip([4, 5, 6])
  .map(..//here i need the initial array)
  .map(..//here i need the zipped array)
  .total(..//

正如您在某些方法中看到的,我需要最后一个计算值,在某些方法中我需要初始值。

此外,在某些情况下,我需要中间值但在计算它们之后。

map(x => x * 1).map(x => x * 2).map(x => x * 4).map(..//i need the result from 2nd map (x*2)

这是一个愚蠢的例子,但说明了问题。

这个问题有没有好的解决方案。

我以为我可以将所有数据保存在对象中,但这会导致代码更冗长,因为在每一步我都必须从对象中设置和获取属性。

另一个例子:对数字求和:[1, 2, 3, 4] -> 10 过滤大于 2的数字:将[1, 2, 3, 4] -> [3, 4] 每个数字与总和相乘:[30, 40]

  Stream.of([1,2,3, 4])
    .sum()
    .filter(// here will be the sum, but i want the initial array and later the sum)
    .map(// here i want the filtered array and the calculated sum)

谢谢

标签: javascriptfunctional-programming

解决方案


如果您需要中间结果,则保存计算:

const initial = Stream.of([1,2,3,4]);
const total   = initial.sum();
const result  = initial.filter(x => x > 2).map(x => x * total);

上面的示例是编写此类代码的最合乎逻辑的方式。我不明白您为什么要编写如下代码:

Stream.of([1,2,3, 4])
    .sum()
    .filter(/* here will be the sum, but i want the initial array and later the sum */)
    .map(/* here i want the filtered array and the calculated sum */)

你的例子令人困惑和误导。无需链接以功能样式编写的代码。


推荐阅读