How can I perform operations in JavaScript just like we do pipeline of operations in Java streams?

前端 未结 7 1080
北海茫月
北海茫月 2020-12-18 20:07

In Java 8 using streams when I chain methods one after the another the execution of operations are performed in pipelined manner.

Example:

List

        
7条回答
  •  無奈伤痛
    2020-12-18 20:28

    If you put each function operation into an array, you can iterate over that array with reduce and pass the last calculated value along in the accumulator until the end of the function array is reached:

    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
    });

    You can't use nums.map because .map will necessarily iterate through the whole input array before resolving to the mapped output array (after which the mapped output array will then have another .map called on it).

提交回复
热议问题