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

前端 未结 7 1101
北海茫月
北海茫月 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:44

    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.

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

提交回复
热议问题