1. What is Corrification

Here’s a reference to Baidu.com:

In computer science, Currying is a technique that converts a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returns a new function that takes the remaining arguments and returns a result.

Summary in one sentence:

Currization is a technique for converting a function that takes multiple arguments into a series of functions that take one argument

What’s the use of currization of functions: I’ll put up a couple of answers:







I still don’t know what it means. That’s okay. I don’t know. Let’s go ahead and read,

2. A simple Coriolization function

function sum (a, b, c) {
    console.log(a + b + c);
}
sum(1.2.3); / / 6
Copy the code

Of course, sum is a simple summation function that takes three arguments and outputs the sum.

Given the need, the first two arguments to sum remain the same and the last argument can be arbitrary. And then you have to wonder, in the function, can you separate out the first two arguments, because the arguments are the same, so you don’t have to do it every time.

If we ignore the implementation inside the function, the call could be written like this: sum(1, 2)(3); Or sum(1, 2)(10); . Take the results of the first two arguments and add them to the third argument.

This is really just a simple application of the Currization of the function.

To summarize: The purpose of Currization is to reduce code redundancy and increase code readability.

3. The benefits of Corrification

1. Parameter reuse 2. Confirm in advance 3

1. Parameter multiplexing

// The above example is a check of the regular. Normally, just call the check function.
// But if I have a lot of places to check for numbers,
// We need to reuse the first parameter reg,
// Call hasNumber, hasLetter, etc.
// Make arguments reusable and easier to call.

// Normal rege.test (TXT)

// The function is wrapped
function check(reg, txt) {
    return reg.test(txt)
}

check(/\d+/g.'test')       //false
check(/[a-z]+/g.'test')    //true

/ / after Currying
function curryingCheck(reg) {
    return function(txt) {
        return reg.test(txt)
    }
}

var hasNumber = curryingCheck(/\d+/g)
var hasLetter = curryingCheck(/[a-z]+/g)

hasNumber('test1')      // true
hasNumber('testtest')   // false
hasLetter('21212')      // false
Copy the code

2. Confirm in advance

We are doing in the process of the project, some wrapped dom manipulation can be common, however, the first written above is common, but we look at the second kind of writing, it is relatively a first written since the execution and returns a new function, it is confirmed which one way can go ahead and avoid judging every time.var on = function(element, event, handler) {
    if (document.addEventListener) {
        if (element && event && handler) {
            element.addEventListener(event, handler, false); }}else {
        if (element && event && handler) {
            element.attachEvent('on'+ event, handler); }}}var on = (function() {
    if (document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false); }}; }else {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on'+ event, handler); }}; }}) ();// The isSupport parameter is set first
var on = function(isSupport, element, event, handler) {
    isSupport = isSupport || document.addEventListener;
    if (isSupport) {
        return element.addEventListener(event, handler, false);
    } else {
        return element.attachEvent('on'+ event, handler); }}Copy the code

3. Delayed operation

// The mechanism that can be implemented, like javascript bind, is called Currying.
Function.prototype.bind = function (context) {
    var _this = this
    var args = Array.prototype.slice.call(arguments.1)
 
    return function() {
        return _this.apply(context, args)
    }
}
Copy the code

4. Packaging Corrification (key points)

function curry (fn, currArgs) {
    return function() {
        let args = [].slice.call(arguments);

        // If the last parameter currArgs is not provided for the first call, args concatenation is not required
        if(currArgs ! = =undefined) {
            args = args.concat(currArgs);
        }

        // recursive call
        if (args.length < fn.length) {
            return curry(fn, args);
        }

        // Recursive exit
        return fn.apply(null, args); }}// You can call curry directly
Copy the code

Resolution:

First, it takes two arguments. Fn refers to the source-processing function sum from the beginning of this article. CurrArgs is the list of arguments passed in when curry is called, such as (1, 2)(3). Looking inside the Curry function, it returns an anonymous function in its entirety. Let args = [].slice.call(arguments); “, meaning to group arguments number. Arguments is an array structure that is not really an array, so you can’t use array methods. With the call method, we can happily use the native methods of arrays for arGs. currArgs ! == undefined, is to solve the recursive call parameter splicing. Finally, determine whether the number of ARgs is equal to the number of parameters of FN (i.e., sum). If the number is equal, all parameters can be passed to FN for output. Otherwise, recursive calls continue until the two are equal.

Let’s test the encapsulated curry:

function sum(a, b, c) {
    console.log(a + b + c);
}

const fn = curry(sum);

fn(1.2.3); / / 6
fn(1.2) (3); / / 6
fn(1) (2.3); / / 6
fn(1) (2) (3); / / 6
Copy the code

5, Currified interview test points

1. Cremation performance

Arguments.length is a bit slower to access than arguments.length (…) And fn. Call (…). It’s usually better than calling fn(…) directly. 4. Creating lots of nested scopes and closures costs money, both in memory and speed

In fact, in most applications, the main performance bottleneck is in the MANIPULATION of DOM nodes, the performance loss of JS is basically negligible, so Curry can be directly trusted to use.

2

// Implement an add method that satisfies the following expectations:
add(1) (2) (3) = 6;
add(1.2.3) (4) = 10;
add(1) (2) (3) (4) (5) = 15;

function add() {
    // On the first execution, an array is defined to store all the parameters
    var _args = Array.prototype.slice.call(arguments);

    // Internally declare a function that uses closure properties to hold _args and collect all parameter values
    var _adder = function() { _args.push(... arguments);return _adder;
    };

    // Take advantage of the toString implicit conversion feature to implicitly convert when finally executed and calculate the final value returned
    _adder.toString = function () {
        return _args.reduce(function (a, b) {
            return a + b;
        });
    }
    return _adder;
}

add(1) (2) (3)                / / 6
add(1.2.3) (4)             / / 10
add(1) (2) (3) (4) (5)          / / 15
add(2.6) (1)                / / 9
Copy the code

Conclusion: Currization of functions is an important concept of functional programming in Javascript. It returns a function of a function. Its implementation method, need to rely on parameters and recursion, by splitting the parameters, to call a multi-parameter function method, in order to reduce code redundancy, increase readability. Front end test: Keri function summary

Reference article: What does Corrification mean for functional programming? Understand the function of the detailed solution of JS function of the curryization