I’ve seen this before, and I kind of know what it is. While reading the Vue source code recently, I saw the cached function used, which made me think the code is quite interesting. I asked sg, read @sunyongjian’s answer, and then went around to currification and higher-order functions.
Currization definition
Wiki has a definition of the curry: in computer science, curry (English: Currying), as Carrie or Gary, is a function of the accept multiple parameters to accept a single parameter (the original function of the first parameter) function, and return to accept the rest of the parameters and return the result of the new function of technology.
Express definitions in JavaScript
Focus on the transformation of a multi-argument function into a function that takes a single argument (the first argument of the original function)
var foo = function(a) {
return function (b) {
return function (c) {
return a+b+c;
};
};
};Copy the code
use
foo(1) // f (b) { return function(c) { return a+b+c } }
foo(1)(2) // f (c) { return a+b+c }
foo(1)(2)(3) // 6Copy the code
It’s a process of gradual elimination. How to understand partial application and currying in functional programming
General Currization functions
The above example explains what a Curryization is, but it is not general because the number of parameters is theoretically impossible to estimate.
The following is an abstract Cremation function
var toCurring = function(fn){
var _args = [];
function cb(){
if(arguments.length === 0) {
return fn.apply(this, _args);
}
Array.prototype.push.apply(_args, [].slice.call(arguments));
return cb;
}
return cb;
}Copy the code
Scenario USES
The use of real scenes can better deepen our understanding, so we use real life scenes to see how the use of Corrification.
Scenario: Bookkeeping, keeping track of how much money is spent each day, adding up the total once a month (or whenever I want to know)
function account(){ var total = []; Function money(p) {if (arguments. Length === 0) {total = total.reduce((sum, arguments. value) => { return sum + value; }, 0) console.log(' total spent ', total+' yuan '); } else {// Record how much money is spent per day total.push(p) console.log(' spent today ', p+' yuan '); } } return money; }Copy the code
So we’ve defined a Currified book of accounts. Let’s use it
var spend = account(); Spend (15) // Spend (30) // Spend (30) // Spend (45)Copy the code
Tip: Higher-order function: A function that takes another function as its argument.