我如何在JavaScript中执行操作就像在Java流中进行操作管道一样?

Jas*_*lly 17 javascript java

在Java 8中,当我一个接一个地链接方法时,使用流以流水线方式执行操作.

例:

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));
Run Code Online (Sandbox Code Playgroud)

输出: -

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
Run Code Online (Sandbox Code Playgroud)

但是当我在javascript中尝试类似时.结果是不同的.在javascript中,第一个操作完成,然后执行第二个操作.例如: -

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));
Run Code Online (Sandbox Code Playgroud)

输出: -

 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
Run Code Online (Sandbox Code Playgroud)

在JavaScript中是否有任何方法使它以管道方式执行操作,并且我在Java程序中获得输出?

这个问题只询问如何在JavaScript中收集,而不是如何在相同类型的方法中更改内部工作.

Nin*_*olz 18

也许稍后(或从不)您可以使用实际的实验 管道运算符|>,它具有以下语法:

expression |> function
Run Code Online (Sandbox Code Playgroud)

通过将函数作为单独的函数并迭代每个管道的流数组,可以实现您想要的结果.

这仅适用于FF.从版本58开始:此功能位于--enable-pipeline-operator编译标志之后.

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);
Run Code Online (Sandbox Code Playgroud)

管道作为功能(功能组合使能管道)与所需功能的闭合相同.

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);
Run Code Online (Sandbox Code Playgroud)


Cer*_*nce 12

如果将每个函数操作放入一个数组中,则可以reduce使用累加器迭代该数组并传递最后一个计算值,直到达到函数数组的末尾:

var nums = [1,2,3,4,5,6 ];
var fns = [
  (x) => {
    x = x * x;
    console.log('map1=' + x);
    return x;
  },
  (x) => {
    x *= 3;
    console.log('map2=' + x);
    return x;
  },
  (x) => {
    console.log(x);
    return x;
  }
];

nums.forEach((num) => {
  fns.reduce((lastResult, fn) => fn(lastResult), num);
  // pass "num" as the initial value for "lastResult",
  // before the first function has been called
});
Run Code Online (Sandbox Code Playgroud)

您无法使用,nums.map因为.map在解析到映射的输出数组之前必须遍历整个输入数组(之后映射的输出数组将.map在其上调用另一个).