This is the second day of my participation in Gwen Challenge.
The interview questions
Add (1)(2)(3)=6
For a moment’s thought, write the following code:
function add(a) {
return function (b) {
return function (c) {
return a + b + c
}
}
}
Copy the code
The interviewer continued, what if the number of parameters after add is 100?
Suddenly it’s not that simple, and this is where the Corrification comes in, so let’s move on.
The function is currified
Function corrification is the transformation of a function that takes multiple arguments into a function that takes a single argument.
For example, the add function takes three arguments.
function add(a,b,c) {
return a + b + c
}
Copy the code
Make the add function a function that takes a single argument.
function add(a) {
return function (b) {
return function (c) {
return a + b + c
}
}
}
Copy the code
So how do you return a function that takes a single argument, b, for any multi-argument function A? We need to implement a Curry function.
The argument to curry’s function is function A. Return a function b. If the number of parameters of B is less than the number of parameters of A, function A cannot be executed and continues to collect parameters. Execute function A until the number of parameters reaches the target number.
var curry = fn= > {
return judge = (. args) = > {
returnargs.length === fn.length ? fn(... args) :(. subArgs) = >judge(... args, ... subArgs)// The number of parameters is not enough, continue to collect parameters}}Copy the code
Using the curry function above, let’s look at the implementation of add
const add = curry((a,b,c) = >{
return a+b+c
})
console.log(add(1) (2) (3)) / / 6
console.log(add(1.2) (3)) / / 6
console.log(add(1) (2.3)) / / 6
Copy the code
Meet the requirements. Add is OK with passing 100 parameters.
Applications/advantages of currization of functions
Parameters of reuse
Curry’s add function, which returns a function each time it is executed, wraps a portion of the arguments and allows them to be reused.
Delay to run
Fn is not executed directly, but is executed after curry processing by gradually obtaining parameters.
Reference documentation
Zh.wikipedia.org/zh/%E6%9F%A… Github.com/mqyqingfeng… Juejin. Cn/post / 684490…