First of all, a brief introduction to what “function currization” is, in the book “javascript Advanced Programming” has the following introduction:

Closely related to function binding is the topic of function currification, which is used to create functions with one or more parameters already set. The basic approach to function curryification is the same as function binding: use a closure to return a function. The difference is that when a function is called, the returned function also needs to set some of the parameters passed in.

To make it easier to understand, we need a function first, and then we need to figure out how to “curryize” it, so let’s create a simple function add

function add(num1,num2){
    return num1 + num2;
}
Copy the code

The goal of currization is to create a function with one or more arguments set, so next create a function that returns a function with one or more arguments set using a closure, called Curry

function curry(fn){
    return function() {}}Copy the code

At this point, the Curry function will be used to “curryize” the function add we just created, so the add function will be passed into Curry as an argument

Next, we continue to complete the Curry function. Since one or more parameters need to be fixed, the parameter must be passed to Curry along with the add function. Since the fixed parameter can be one or more, we use the array slice method to cut it out of the parameter list

functioncurry(fn){ var args = Array.slice.call(arguments,1); // the zeroth bit is fnreturn function() {}}Copy the code

After the fixed parameters are intercepted, the incoming parameters are retrieved, merged, passed to add, and the result of the add function is returned

functioncurry(fn){ var args = Array.prototype.slice.call(arguments,1); // the zeroth bit is fnreturn function(){ var innerArgs = Array.prototype.slice.call(arguments); Var finalArgs = args. Concat (innerArgs); var finalArgs = args. / / mergereturnfn.apply(null,finalArgs); }}Copy the code

Suppose the first argument to the fixed add method is the number 5

var curridAdd = curry(add,5)

In this case, curridAdd is the Currized function

CurridAdd (2) // The fixed argument is 5, the passed argument is 2, the result is 7

You can also fix 2 parameters

Var curridAdd = curry (add, 5, 1)

CurridAdd (2) // The fixed arguments are 5 and 1, and the result is 6 regardless of the number of arguments passed in

At this point, a simple Curryization function has been implemented