The function is currified
Function currification refers to the technique of converting a function that takes multiple arguments into a function that takes a single argument and returns a new function that takes the remaining arguments and returns the result.
Main functions and characteristics
- Parameters of reuse
// function check(reg, 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') // falseCopy the code
- Confirmation in advance
var onFn = 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); }}; }}Copy the code
The onFn can be executed ahead of time to save the method that has been checked for compatibility so that the next time it is executed it does not need to be checked again for compatibility.
- Delay the
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
The mechanism that bind implements is Currying.
A classic interview question
// Implement an add method that meets the following expectations: add(1)(2)(3) = 6; add(1, 2, 3)(4) = 10; add(1)(2)(3)(4)(5) = 15; Function add() {var argArr = array.from (arguments); function add() {var argArr = array.from (arguments); Var _adder = function() {argarr.push (...) {var _adder = function() {argarr.push (... arguments); return _adder; }; ToString = function () {console.log(1); toString = function () {console.log(1); return argArr.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) // 9Copy the code
Refer to the article
Detailed solution of JS function coriolization
A further elaboration of the Currization of functions