Home >Web Front-end >JS Tutorial >An in-depth analysis of function currying in JavaScript_javascript skills

An in-depth analysis of function currying in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:02:551343browse

The origin of curry is the name of mathematician Haskell Curry (the programming language Haskell is also named after him).

Currying is usually also called partial evaluation. Its meaning is to pass parameters to a function step by step. After each parameter is passed, the parameters are partially applied and a more specific function is returned to accept the remaining parameters. This can be nested multiple levels in the middle. The function accepts some parameters until the final result is returned.

Therefore, the process of currying is a process of gradually passing parameters, gradually narrowing the applicable scope of the function, and gradually solving the problem.

Currying a summation function
According to the step-by-step evaluation, let’s look at a simple example

var concat3Words = function (a, b, c) { 
  return a+b+c; 
}; 
 
var concat3WordsCurrying = function(a) { 
  return function (b) { 
    return function (c) { 
      return a+b+c; 
    }; 
  }; 
}; 
console.log(concat3Words("foo ","bar ","baza"));      // foo bar baza 
console.log(concat3WordsCurrying("foo "));         // [Function] 
console.log(concat3WordsCurrying("foo ")("bar ")("baza")); // foo bar baza 

As you can see, concat3WordsCurrying("foo ") is a Function. Each call returns a new function, which accepts another call and then returns a new function until the final result is returned. Distribution solution, Progress step by step. (PS: The characteristics of closure are used here)

So now we go one step further. If we require more than 3 parameters to be passed, we can pass as many parameters as we want. When no parameters are passed, the result is output?

First let’s do a common implementation:

var add = function(items){ 
  return items.reduce(function(a,b){ 
    return a+b 
  }); 
}; 
console.log(add([1,2,3,4])); 

But if it is required to multiply each number by 10 and then add it up, then:

var add = function (items,multi) { 
  return items.map(function (item) { 
    return item*multi; 
  }).reduce(function (a, b) { 
    return a + b 
  }); 
}; 
console.log(add([1, 2, 3, 4],10)); 

Fortunately, there are map and reduce functions. If we follow this model and now add 1 to each item and then summarize it, then we need to replace the function in map.

Let’s take a look at the currying implementation:

var adder = function () { 
  var _args = []; 
  return function () { 
    if (arguments.length === 0) { 
      return _args.reduce(function (a, b) { 
        return a + b; 
      }); 
    } 
    [].push.apply(_args, [].slice.call(arguments)); 
    return arguments.callee; 
  } 
};   
var sum = adder(); 
 
console.log(sum);   // Function 
 
sum(100,200)(300);  // 调用形式灵活,一次调用可输入一个或者多个参数,并且支持链式调用 
sum(400); 
console.log(sum());  // 1000 (加总计算) 

The above adder is a curried function. It returns a new function. The new function can accept new parameters in batches and delay the calculation until the last time.

Universal currying function

The more typical currying will encapsulate the last calculation into a function, and then pass this function as a parameter to the currying function, which is clear and flexible.

For example, if each item is multiplied by 10, we can pass the processing function as a parameter:

var currying = function (fn) { 
  var _args = []; 
  return function () { 
    if (arguments.length === 0) { 
      return fn.apply(this, _args); 
    } 
    Array.prototype.push.apply(_args, [].slice.call(arguments)); 
    return arguments.callee; 
  } 
}; 
 
var multi=function () { 
  var total = 0; 
  for (var i = 0, c; c = arguments[i++];) { 
    total += c; 
  } 
  return total; 
}; 
 
var sum = currying(multi);  
  
sum(100,200)(300); 
sum(400); 
console.log(sum());   // 1000 (空白调用时才真正计算)

In this way, sum = currying(multi), the call is very clear, and the use effect is also brilliant. For example, if you want to accumulate multiple values, you can use multiple values ​​as parameters sum(1,2,3), which can also be supported Chained calls, sum(1)(2)(3)

The basics of currying

The above code is actually a high-order function. A high-order function refers to a function that operates on functions. It receives one or more functions as parameters and returns a new function. In addition, it also relies on the characteristics of closures to save the parameters entered in the intermediate process. That is:

Functions can be passed as parameters
Functions can be used as function return values ​​
Closure
The role of currying
Delayed calculation. The above example is relatively easy to explain.

Parameter reuse. When the same function is called multiple times and the parameters passed are mostly the same, then the function may be a good candidate for currying.

Dynamicly create functions. This can be done by dynamically generating a new function to handle the subsequent business after partially calculating the results, thus eliminating repeated calculations. Or you can dynamically create a new function by partially applying a subset of the parameters to be passed into the calling function to the function. This new function saves the parameters that are passed in repeatedly (you don’t have to pass them in every time in the future). For example, the event browser adds a helper method for events:

 var addEvent = function(el, type, fn, capture) { 
   if (window.addEventListener) { 
     el.addEventListener(type, function(e) { 
       fn.call(el, e); 
     }, capture); 
   } else if (window.attachEvent) { 
     el.attachEvent("on" + type, function(e) { 
       fn.call(el, e); 
     }); 
   } 
 }; 

Every time you add event processing, you need to execute if...else.... In fact, only one judgment is needed in a browser. A new function is dynamically generated based on the result of one judgment, so there is no need to do so in the future. Recalculate.

var addEvent = (function(){ 
  if (window.addEventListener) { 
    return function(el, sType, fn, capture) { 
      el.addEventListener(sType, function(e) { 
        fn.call(el, e); 
      }, (capture)); 
    }; 
  } else if (window.attachEvent) { 
    return function(el, sType, fn, capture) { 
      el.attachEvent("on" + sType, function(e) { 
        fn.call(el, e); 
      }); 
    }; 
  } 
})(); 

In this example, after the first if...else... judgment, part of the calculation is completed, and a new function is dynamically created to process the parameters passed in later. This is a typical currying.

Function.prototype.bind method is also curried application

Different from the direct execution of the call/apply method, the bind method sets the first parameter as the context of function execution, and the other parameters are passed to the calling method in turn (the body of the function itself is not executed and can be regarded as delayed execution), and Dynamic creation returns a new function, which conforms to the characteristics of currying.

var foo = {x: 888}; 
var bar = function () { 
  console.log(this.x); 
}.bind(foo);        // 绑定 
bar();           // 888 

The following is a simulation of the bind function. testBind creates and returns a new function. In the new function, the function that actually performs the business is bound to the context passed in as the actual parameter, and the execution is delayed.

Function.prototype.testBind = function (scope) { 
  var fn = this;          //// this 指向的是调用 testBind 方法的一个函数, 
  return function () { 
    return fn.apply(scope); 
  } 
}; 
var testBindBar = bar.testBind(foo); // 绑定 foo,延迟执行 
console.log(testBindBar);       // Function (可见,bind之后返回的是一个延迟执行的新函数) 
testBindBar();            // 888 

Here we should pay attention to the understanding of this in prototype.

The above article is an in-depth analysis of function currying in JavaScript. This is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn