Function currification
-
currying
In computer science, Currying is a technique that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the original function), and returns a new function that accepts the remaining parameters and returns the result.
To put it simply, fix some parameters and return a function that accepts the remaining parameters.
In fact, it is to use the closure to return a delayed execution function.
It may be a little difficult to understand the corrilization only by looking at the text description. Take a very classic example:
// This example is currification, which can also be said to be part of the application // For what is partial application, we will not discuss it here function add(num1, num2) { return num1 + num2; } function curry(func) { let args = [].slice.call(arguments, 1); return function() { let innerArgs = [].slice.call(arguments); let finalArgs = [...args, ...innerArgs]; return func.apply(null, finalArgs); } } // Get delayed execution function let curriedAdd = curry(add, 5); // Functions that can be multiplexed curriedAdd(1); // 6 curriedAdd(2); // 7
Looking at the simple example above, we can now implement the curriedAdd(1)(2, 3)(4) currification function as follows:
function aidCurry(func) { let args = [].slice.call(arguments, 1); return function() { return func.apply(null, [...args, ...arguments]); } } function curry(func, length) { length = length || func.length; return function() { // The passed in parameter is 0, indicating the returned result if (arguments.length != 0 && arguments.length < length) { let finalArgs = [func, ...arguments]; // When the number of parameters is insufficient, closures are used to store the passed in parameters return curry(aidCurry.apply(null, finalArgs), length - arguments.length); } else { // If the number of parameters is enough or it ends halfway, the result will be returned return func.apply(null, arguments); } }; } // The length is 4, indicating that the result will be returned when the incoming parameters reach 4 let curriedAdd = curry(function add() { return [...arguments].reduce((acc, cur) => acc + cur); }, 4); // 4 incoming parameters curriedAdd(1)(2, 3)(4); // 10 // Halfway end curriedAdd(1)(2, 3)(); // 6 // error: not a function curriedAdd(1)(2)()(3); // Use () to return the result, which is no longer a function curriedAdd(1)(2, 3)(4)(); // The passed in parameters are already 4, so the returned result is not a function