javascript-function currying
Curry is a conversion process that transforms a function that accepts multiple parameters into a function that takes a single parameter (the first parameter of the original function), and returns a new function that takes the remaining arguments and returns the result if the other parameters are necessary.
That is, a fixed partial parameter that returns a function that takes the remaining parameters, also called a partial calculation function, to narrow down the scope of application and create a more targeted function.
For example, I want to create a self-introduction function, everyone just enter their name, gender, age can be. However, when a uses this function, each call must enter their own name, gender, actually only the age changes, for which a will generate a curry self-introduction function, where the name and gender are fixed parameters.
Please see GitHub for related codes.
function curry(fn){ varargs =Array. Prototype.slice.call (arguments,1);return function(){ varInnerargs =Array. Prototype.slice.call (arguments);varFinalargs = Args.concat (Innerargs);returnFn.apply (NULL, Finalargs); }; } function selfintroduction(name, gender, age){Console.log (' Hi, I am '+ name +', '+ Age +' years old '+'. I am a '+ Gender +'. '); }varCurriedselfintroduction = Curry (selfintroduction,' A ',' man '); Curriedselfintroduction (' a '); Curriedselfintroduction (' A '); Curriedselfintroduction (' + ');
Results after execution.
Of course, we can also write a curry function that binds to the new scope.
function curry (FN, context) { var args = array . Prototype . Slice.call (arguments , 2 ); return function () { var Innerargs = array . Prototype.slice . Call (arguments ); var Finalargs = Args.concat (Innerargs); return fn.apply (context, Finalargs); }; }
Although the curry function is already very good, it also allows you to spend a little bit of your mind on the order of the parameters of the function you define. The function of curry allows and encourages you to separate complex functions into smaller and easier to analyze parts. These small logical units are clearly easier to understand and test, and then your application becomes a clean and neat combination of small units. So if you can use the Curry function properly, it will make your JS code more elegant.
Note: It is recommended that you take a look at the proxy in ES6 (ES2015), which is another way to preprocess a function.
javascript-function currying