就像我们在Java流中执行流水线一样,如何在JavaScript中执行操作? [英] How can I perform operations in JavaScript just like we do pipeline of operations in Java streams?
问题描述
在使用流的Java 8中,当我一个接一个地链接方法时,以流水线方式执行操作.
In Java 8 using streams when I chain methods one after the another the execution of operations are performed in pipelined manner.
示例:
List<Integer> nums = Arrays.asList(1,2,3,4,5,6);
nums.stream().map(x->{
x = x * x;
System.out.println("map1="+x);
return x;
}).map(x->{
x = x * 3;
System.out.println("map2="+x);
return x;
}).forEach(x-> System.out.println("forEach="+x));
输出:-
map1=1
map2=3
forEach=3
map1=4
map2=12
forEach=12
map1=9
map2=27
forEach=27
map1=16
map2=48
forEach=48
map1=25
map2=75
forEach=75
map1=36
map2=108
forEach=108
但是当我在javascript中进行类似尝试时,结果却不同.与javascript中一样,第一个操作完成了,然后执行了第二个操作.示例:-
But when I tried similarly in javascript.The result is different.As in javascript first operation gets completed and then second operation is performed.Example:-
var nums = [1,2,3,4,5,6 ];
nums.map(x => {
x = (x * x);
console.log('map1='+x);
return x;})
.map(x => {
x = x * 3;
console.log('map2='+x);
return x;})
.forEach(x=> console.log('forEach='+x));
输出:-
map1=1
map1=4
map1=9
map1=16
map1=25
map1=36
map2=3
map2=12
map2=27
map2=48
map2=75
map2=108
forEach=3
forEach=12
forEach=27
forEach=48
forEach=75
forEach=108
JavaScript中是否有任何方法可以使其以管道方式执行操作,并且获得Java程序中的输出?
Is there any way in JavaScript to make it performs operations in a pipeline manner, and I get output as in the Java program?
此问题仅询问如何在JavaScript中收集内容,而不询问内部工作方式如何变化相同类型的方法.
推荐答案
Maybe later (or never) you can use the actual experimental pipeline operator |>
, which has the following syntax:
expression |> function
通过将这些函数作为单独的函数并为每个管道迭代流数组,可以实现所需的结果.
Your wanted result could be achieved by taking the functions as separate functions and iterate the stream array for each pipe.
这仅在FF中有效.从58版开始:此功能位于-enable-pipeline-operator
编译标志的后面.
This works only in FF. From version 58: this feature is behind the --enable-pipeline-operator
compile flag.
const
a = x => { x = x * x; console.log("map1=" + x); return x; },
b = x => { x = x * 3; console.log("map2=" + x); return x; },
c = x => console.log("forEach=" + x)
var nums = [1, 2, 3, 4, 5, 6];
nums.forEach(v => v |> a |> b |> c);
The same with a pipe as function (function composition enabling piping) with a closure over the wanted functions.
const
pipe = (...functions) => input => functions.reduce((acc, fn) => fn(acc), input),
a = x => { x = x * x; console.log("map1=" + x); return x; },
b = x => { x = x * 3; console.log("map2=" + x); return x; },
c = x => console.log("forEach=" + x)
var nums = [1, 2, 3, 4, 5, 6],
pipeline = pipe(a, b, c);
nums.forEach(pipeline);
这篇关于就像我们在Java流中执行流水线一样,如何在JavaScript中执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!