function currying

  First look at the definition of function currying: Function currying refers to a transformation process, in which a function that accepts multiple parameters is transformed into a nested function. These nested functions only Takes one parameter. To give a simple example to experience, we write an add function that accepts two parameters and returns the sum of the parameters.

const add = (x,y) => x + y;

  Simple call, add(2, 3) returns 5, nothing to say. Now let's curry this function. Currying, each function accepts only one parameter, so we must first declare a function that accepts one parameter, assuming x, 

function addCurried(x){
   }

  Since add accepts two parameters, there is one parameter y left, and only functions can accept parameters, so addCurried also returns a function that accepts parameter y.

function addCurried (x) {
    return function(y) {
        
    }
}

  At this time, both parameters are obtained, and the calculation can be performed. So you can write return x + y directly in the returned function;

function addCurried (x) {
    return function(y) {
        return x + y;
    }
}
  Now we have completed the currying of the function add. A function that takes two parameters becomes two nested functions, each of which takes only one parameter. After currying is completed, the function call has also changed, and only one function is returned at a time.
let fn = addCurried(2);
console.log(fn)

  So call again

let result = fn(3);
console.log(result);

  Simplified way of calling

let result = addCurried(2)(3);
console.log(result);

  Now we curry the add function step by step. If we encapsulate this process, we can curry any function that accepts two parameters. We name this function curry, it first accepts a curried function as a parameter, and then returns our addCurried function above

function curry(fn) {
    return function addCurried(x) {
        return function(y) {
            return fn(x, y)
        }
    }
}

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325217110&siteId=291194637