🎯 summary

Using the feature of closures, the parameters are passed into the original function in batches, one to one, and after collecting all the parameters, the final function is executed to get the result.

curry

  1. The key point

    • Use closures to save previously passed parameters
    • When all arguments are passed, the function is not returned, but the last function returned is executed, and the result is obtained.
    • When the last function returned is executed, all the arguments are actually passed to the original function and executed.
  2. Simple implementation

    • The rest argument is used to retrieve the superfluous arguments of the function
    /* The argument can be passed */ twice
    function curry(fn, ... initArgs) {
      return function (. args) {
        returnfn(... initArgs, ... args) } }function sum(a, b, c) {
      return a + b + c
    }
    console.log(curry(sum)(1.2.3))  / / 6
    console.log(curry(sum, 1) (2.3))  / / 6
    console.log(curry(sum, 1.2) (3))  / / 6
    console.log(curry(sum, 1.2.3) ())/ / 6
    Copy the code