This is the 19th day of my participation in the August More Text Challenge

Kerrization of JS functions

In computer science, Currying, also translated as carryization or callization, is a technique of converting a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returning a new function that takes the remaining arguments and returns a result. The technique was named by Christopher Strackey after logician Haskell Gary, although it was invented by Moses Schonfinkel and Gottlob Frege.

Look at the word, it’s kind of patronizing, and the explanation is kind of confusing, but look at the example.

Add (1)(2)(3)(4)=10;

The sum that we see a lot in everyday life is something like this: add(1,2,3) = 6;

function add(x, y, z) {
  return x + y + z;
}
console.log(add(1.2.3)); / / 6
Copy the code

There’s another way to write it:

var add = function(x) {
  return function(y) {
    return function(z) {
      returnx + y + z; }}}var addOne = add(1);
var addOneAndTwo = addOne(2);
var addOneAndTwoAndThree = addOneAndTwo(3);

console.log(addOneAndTwoAndThree);
Copy the code

Here we define an add function that takes an argument and returns a new function. After you call Add, the returned function remembers the first argument to add in the form of a closure.

How can I say, it looks like the function is implemented, is a little silly, hahaha ~~

Of course, we know that ES6 can change the above code again:

const add = x= > y= > z= > x + y + z;
Copy the code

So we use the concept of Currization to implement an automatic Currization function:

Const _args = […arguments]; const _args = […arguments]; ;

You then declare a function internally that takes advantage of the closure properties and stores it in _args and collects all the parameter values.

We then take advantage of the toString implicit conversion feature, and when the final implicit conversion is performed, the final value is computed and returned.

function add() {
  const _args = [...arguments];
  function fn() { _args.push(... arguments);return fn;
  }
  fn.toString = function() {
    return _args.reduce((sum, cur) = > sum + cur);
  }
  return fn;
}
Copy the code

In the interview, because there is no actual project application, usually a question like this, to test our understanding of the function Of the Currization;

Of course, we often use this. Traditional function calls require pre-determination of all arguments, and if you only get a few arguments in one part of the code and a few arguments in another part of the code, then corrification can be used.