I need help understanding the rest and spread operator

后端 未结 3 427
無奈伤痛
無奈伤痛 2021-01-15 09:13

This is the code:

const Pipe = (...fns) => fns.reduce((f,g) => (...args) => g(f(...args)));

So by (...fns) the fns arguments beco

3条回答
  •  暖寄归人
    2021-01-15 09:43

    For better understanding I have translated the code to block level as below trying to explain the code in question for a novice developer which helps. For better implementation @naomik has solution.

    ES6

    const Pipe = (...fns) => {
        return fns.reduce((f, g) => {
            return (...args) => {
                return g(f(...args))
            }
        })
    };
    

    Equivalent ES5 implementation:

    var Pipe = function () {
        var fns = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            fns[_i] = arguments[_i];
        }
        return fns.reduce(function (f, g) {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return g(f.apply(void 0/*Undefined or can use 'null'*/, args));
            };
        });
    };
    

    Part by part breakdown:(read the code comments for better understanding)

    const inc = (num) => num+1 //Function to increment the number
    const dbl = (num) => num*2 //Function double's the number
    const sqr = (num) => num*num //Function Square's the number
    
    /*Function breakdown*/
    const _pipe = (f, g) => (...args) => g(f(...args)); //Second part
    const Pipe = (...fns) => fns.reduce(_pipe); //First part
    
    const incDblSqr = Pipe(inc, dbl, sqr) //Piping all the functions
    const result = incDblSqr(2) // Piped function
    console.log(result) // ((2+1)*2) ^ 2  = 36
    

    Explaination:

    The code in question helps to pipe the result from one function to another function.

    Step by step process of above code:

    • First number is incremented by 1
    • The result after increment is accumulated and piped to another function where the number gets multiplied by 2 (doubling it)
    • Finally the doubled number is squared next function.

    All these are achieved using closures which has access to the reducing arguments (Read the article linked below for clarity).

    Conclusion: The code in question helps to pipe the n-number of functions that operates on the result emitted by previous function.


    Best article by Andrew L. Van Slaars: https://vanslaars.io/post/create-pipe-function/

    Please read the above article for clarity and also @naomik solution

提交回复
热议问题