# [front end -- interview] common interview questions (VII) -- detailed explanation of JS function coritization

2021-08-27 08:21:07

This is my participation 8 The fourth of the yuegengwen challenge 19 God , Check out the activity details ：8 Yuegengwen challenge

# JS The function is coriolized

In computer science , currying （ English ：Currying）, Another translation is Karenization or Kalilization , It is to transform a function that accepts multiple parameters into a single parameter （ First parameter of the original function ） Function of , And return the technique of taking the remaining arguments and returning the result of the new function . This technology was developed by Christopher · Strech With logicians Haskell · Gary Named , Even though it is Moses Schönfinkel and Gottrob · Frege invented .

Look at the word , It's very tall , The explanation looks as if you don't understand , But just look at the example .

In daily life, we often see that the way of seeking peace is actually like this ：add(1,2,3) = 6;

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

There's another way to write it ：

var add = function(x) {
return function(y) {
return function(z) {
return x + y + z;
}
}
}

Copy code

Here we define a add function , It takes a parameter and returns a new function . call add after , The function returned is remembered by closure add The first parameter of .

How to put it? , It seems that the function is realized , Just a little silly , Ha ha ha ha ~~

Of course we know ES6 You can change the code above ：

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

Then we use the concept of coritization to realize an automatic Coriolis function

First of all, when we first implemented , First define an array to store all the parameters const _args = [...arguments];;

Then declare a function inside , Using the properties of closures, save in _args And collect all parameter values .

Then use toString Characteristics of implicit conversion , When the implicit conversion is finally performed , Calculate the final value and return .

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

In the interview , Because there is no actual project application , There is usually a topic similar to this , Let's take a test of our understanding of function coritization ;

Of course, we usually apply it to , Traditional function calls require all arguments to be determined in advance , If you get only part of the arguments in one place of the code , Get another part of the arguments in another place , At this time, corihua can use .