preface
What is a function Corrification? The so-called “Corrification” is simply to transform a multi-parameter function into a single-parameter function.
Write a simple little example:
Function add(a, b, c) {return a + b + c} add(1, 2, 3) // 6 // let addCurry = curry(add) addCurry(1)(2Copy the code
This example is obviously incomplete. How is the Curry function implemented? So let’s implement that.
Implementing the Curry function
- You can understand the so-called Currification function, which encapsulates == a series of processing steps ==, calculates the parameters in a closure, and passes in the parameters to be processed.
- The idea is to use closures to store the parameters passed in, and when enough of them are passed in, the function is executed.
By implementing the curry function, the function goes from passing multiple arguments in one call to passing one argument in multiple calls.
Write out the curry function using ES6 syntax :(much cleaner and easier to understand)
const curry = fn => judge = (... args) => args.length >= fn.length ? fn(... args) : (... arg) => judge(... args, ... arg) // Test const fn = curry(function(a, b, c) { console.log([a, b, c]); }) add(1, 2, 3) // 6 add(1, 2)(3) // 6 add(1)(2)(3) // 6 add(1)(2, 3) // 6Copy the code
- Call the Curry function to get the arguments of the function fn.
- Define a new function judge that accepts arguments as
. The args.
- Check whether the length of the parameters accepted by the new function is greater than or equal to the length of the remaining parameters received by fn
- If the requirements are met, the fn function is executed and the parameters of the new function are passed in
- Otherwise, return a new anonymous function that takes all the parameters passed in
. args
Stored in thearg
Array, and the anonymous function is executed, after the previously received parameter array and the current parameter array merge, put in the above logic, judge in the function, repeat step 3.
conclusion
You should get a basic idea of what a function currization is by writing a small example and implementing the Curry function: A closure to store the parameters passed in, and when the number of parameters passed in is sufficient to execute the function, the function is executed. It’s not that deep, but it’s a little rewarding.