I need help understanding the rest and spread operator

后端 未结 3 404
無奈伤痛
無奈伤痛 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 10:03

    Well @naomik beat me to just about the same answer but I thought I'd still share what I had to help you explain how the function works in a possibly less cryptic way. (Maybe)

    I think you already know how the "..." works (and in case you didn't then naomik's answer should help with that :D)

    Here is another version of that same pipe function expect re-written to better explain what's going on using assignments just to explain the point.

    Array.prototype.reduce calls the "reducer", toASingleFunction, multiple times--one call for each function in functionsToPipe. The currentFunctionToPipe is first x => x + 1 then x => x * 2 and so on...

    The first value of newFunction is theIdentityFunction and the reducer returns another function nextNewFunction. As the name suggests, it becomes the next newFunction in the next call to the "reducer" (toASingleFunction).

    Once all the items in functionsToPipe have been reduced, the final newFunction is returned as finalPipeFunction.

    /**
     * `x` goes to itself
     */
    const theIdentityFunction = x => x;
    
    /**
     * the `reducer` that reduces the array of functions into a single function
     * using the value from the last function as the input to the next function
     */
    const toASingleFunction = (newFunction, currentFunctionToPipe) => {
      const nextNewFunction = function(value) { // i'm not using arrow functions here just to explicitly show that `nextNewFunction` is, in fact, a function
        const valueFromLastFunction = newFunction(value);
        return currentFunctionToPipe(valueFromLastFunction);
      }
      return nextNewFunction;
    };
    
    const pipe = (...functionsToPipe) => {
      const finalPipeFunction = functionsToPipe.reduce(toASingleFunction, /* start with */ theIdentityFunction);
    
      return finalPipeFunction;
    }
    
    const f = pipe(
      x => x + 1,
      x => x * 2,
      x => x * x
    );
    
    console.log(f(2)) // ((2 + 1) * 2) ^ 2 === 36

    Maybe this helps?

    good luck!

提交回复
热议问题