PS: refer to some blogs, sort out for their own review ~

What is a function keratology

Curry is the concept of functional programming. Curry’s concept is simple: Call a function with just a few arguments and let it return a function that handles the rest.

To put it simply: each time a function is called, it takes only a few arguments and returns a function until all the arguments are passed.

const add = (x, y) = > x + y;
add(1.2);
Copy the code

Change to a function that takes one argument at a time

const add = x= > y= > x + y;
add(1) (2);
Copy the code

add(1)(2)(3)

const add = x= > y= > z= > x + y + z;
console.log(add(1) (2) (3));
Copy the code

It may not seem that difficult, but what if the interviewer’s request is to implement an Add function that supports all of the following? Or don’t know how many parameters the prop will pass?

Implementation idea:

The main idea is to determine whether the number of parameters (args. Length) of the current function is greater than or equal to the number of parameters required by the original function (fn.length), if so, then execute the current function; If it is less than, a function is returned.

const curry = (fn, ... args) = > 
    // The number of arguments to a function can be accessed directly from the.length attribute of the function number
    args.length >= fn.length // This judgment is critical!!
    // If the number of arguments passed to fn is greater than or equal to the number of arguments in the original function, the function is executed directly? fn(... args)/** * If the number of arguments passed in is less than the number of arguments in the original function fn *, the current function continues to be currized, returning a function that takes all arguments (current and remaining arguments) */
    : (. _args) = >curry(fn, ... args, ... _args);function add1(x, y, z) {
    return x + y + z;
}
const add = curry(add1);
console.log(add(1.2.3));
console.log(add(1) (2) (3));
console.log(add(1.2) (3));
console.log(add(1) (2.3));
Copy the code

Lodash is a powerful library of utility functions, such as throttling, stabilization, deep copy, and so on, that we can use directly once we introduce LoDash.

The role of chemical chemistry

There are three main functions: parameter reuse, early return, and delayed execution

Let’s explain it briefly:

Parameter multiplexing: take the above function f for example, as long as you pass in a parameter Z, execute, the calculation result is 1 + 2 + z, the two parameters 1 and 2 can be directly multiplexed.

Early return and delayed execution are also easy to understand, because each time a function is called, it takes only a few arguments and returns a function (early return) until all the arguments (delayed execution) have been passed.