javascript - 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)
谢谢
解决方案
如果您需要中间结果,则保存计算:
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 */)
你的例子令人困惑和误导。无需链接以功能样式编写的代码。
推荐阅读
- c# - 在 ASP.NET Core 5 中手动解析时未调用 ITenantIdentificationStrategy
- javascript - 如何更新飞镖中的模型
- excel - Excel 公式问题
- sql - 获取“缺少右括号”错误 SQL--找不到问题
- linux - 如何转义通过 bash -c 传递给 bash 的命令?
- python - 如何计算列表中的选票并将其存储在字典中以跟踪选票数量
- java - 将 Predicate<> 转换为子类型
- javascript - 如何在定义后立即使用变量 - js
- pdf-generation - Sejda HTML to PDF:如何在显示表格的所有页面上保留标题?
- python - 如何在 AllenNLP 中加载微调的 sciBERT 模型?