Definition: According to Baidu Encyclopedia, cremation is “the technique of converting a function that takes multiple parameters into a function that takes a single parameter (the first parameter of the original function), and returning a new function that takes the remaining parameters and returns the result”. In layman’s terms, if an ordinary function takes two or more arguments, currization is the splitting of the function into two or more functions, one of which takes the arguments and the other functions take the other arguments and process them.

It’s hard to understand, isn’t it? Let’s start with a chestnut.

function isStr (reg, prop) {
  return reg.test(prop);
}
function isNum (reg, prop) {
  return reg.test(prop);
}
console.log(isStr(/[a-z]+/g, 'abcd')); // true
console.log(isNum(/[0-9]+/g, 123)); // true
Copy the code

If we need to verify a string or a number, it is very common packaging two functions, by passing in a regular in the judgement and strings, but if we are late new requirements, such as I want to test whether a string is id, whether for mobile phone number, whether for E-mail, etc., so we want to encapsulate N function, and these functions have a lot of the same part, This creates redundant code, and currization is used to reduce this redundant code. For example, our example above can be optimized with currization.

function check (reg) {
  return function (text) {
    return reg.test(text);
  };
}

var isStr = check(/[a-z]+/g);
var isNum = check(/[0-9]+/g);

console.log(isStr('abc')); // true
console.log(isNum(123)); // true
Copy the code

If you look at this, you might say, this doesn’t reduce any code from the original, and it looks very complicated, but let’s think about it. If we add a validation, such as checking whether it is a mailbox, then we just need to add a line of code to the optimized code, namely:

var isEmail = check(/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+/g);
Copy the code

In the optimized code above, the first parameter is already fixed. No matter where we call, we only need to pass in the string that needs to be validated. This can reduce the code first and avoid misoperation second.

At this point, the role of the JS function coriolization comes out. Parameter reuse, also known as fixed variable parameter 2. Reduce code redundancy 3. Increase code readability

Let’s look at a classic interview question.

Write sum such that sum(1)(2) === sum(1, 2);function sum (x) {
  if (arguments.length === 2) {
    return x + arguments[1];
  }
  return function(y){
    returnx + y; }}Copy the code

So by this point, I’ve done all I can do about the corrification of functions.