Explanation: Call a function by passing it only a few arguments and have it return a function to process the rest.

First, add(1), (2), (3)

const add = function(x){
    return function(y){
        return function(z){
            return x+y+z
        }
    }
}
console.log(add(1)(2)(3));
Copy the code

Simplified to the arrow function

const add = x => y => z => x + y + z;
console.log(add(1)(2)(3));
Copy the code

In this case, the function can only take one parameter, which has to be rewritten in order to implement the following structure

Add (1)(2) add(1)(2) (3) add(1, 2)(3); add(1)(2, 3);Copy the code

If you only implement the parentheses add(1)(2), you can return a function internally to receive the function arguments in the second parenthesis.

function sum(){ var args = Array.prototype.slice.call(arguments) //1. Let inner = function(){args.push(... Arguments) //3. Put the arguments received by the return inner into args, where closure is used. let total = args.reduce((prev,item) => prev+item) return total } return inner //2. } console.log(sum(6)(2))Copy the code

Here, you can only receive two function arguments, and if you want to receive more arguments you need to return a function inside inner, which is obviously not appropriate for more complex scenarios.

The collection of function parameters is achieved by continuing to return inner inside the inner, but since the function has already returned inside, it cannot process and return the args

function sum(){ var args = Array.prototype.slice.call(arguments) let inner = function(){ args.push(... arguments) console.log(args) return inner } return inner }Copy the code

This is done by rewriting the toString method

function sum(){ var args = Array.prototype.slice.call(arguments) let inner = function(){ args.push(... arguments) return inner } inner.toString = function(){ return args.reduce((prev,curr) => prev+curr) } return inner }Copy the code

The sum method is implemented, and the parameters passed in May not be qualified

If you limit the parameter passed to 3

Such as: sum (1) (2) (3)

This can be done by encapsulating a curry function

var sum = function(a,b,c){ return a+b+c } console.log(sum.length) function curry(fn, currargs){ return function (){ let args = Array.prototype.slice.call(arguments) if(currargs ! If (args. Length < fn.length){return curry(fn,args)} If (args. Length == fn. Length){return fn. Apply (null,args)}else{return "error"}}} var fn = curry(sum) console.log(fn(1)(2)(3))//6Copy the code