Initial corrification

Just realized that the Coriization function started with an interview question:
add(1)(2)(3)(4) = 10;
Copy the code
  • Add (1) (2)(3)(4)
  • The idea is that add(1) returns a function. Therefore, you can splice (2) and continue to execute until the end
  • The function structure is shown in the figure below
function add (a) {
	return function (b) {
		return function (c) {
			return function (d) {
				return a + b + c + d
			}
		}
	}
}
Copy the code
  • This method is certainly not beautiful for programmers, so use coriolized function classes to solve the problem
  • Let’s see how corrification works
  • Principle: Use closures to turn a function that takes multiple arguments into a function that takes one or more arguments step by step
// fixed length: Function fn(a,b,c,d){//reduce; Add arguments and return [...arguments].reduce((a,b)=>a+b)} // Wrap function currying(fn){function currying(fn){// get a number of years, which is four for fn(a,b,c,d),len = 4; let len = fn.length; Return function _c(){// Args = [...args,...arguments]; If (args. Length <len){// If (args. Length <len){if(args. Length <len){// If (args. Length <len){// If (args. Length <len){// If (args Fn. apply(this,args)}}} let add = currying(fn); // execute res = 10 let res = add(1)(2)(3)(4);Copy the code
  • So the first case is constant length, what about indefinite length?
  • For indefinite length, we set a boundary condition: that is, the first time the passed parameter is empty, it means that the parameter is received
Function fn2(){return [...arguments].reduce((a,b)=>a+b)} function currying2(){let args = []; return function _c(){ args = [...args,...arguments]; If (arguments.length){return _c}else{return fn. Apply (this,args)}} let add2 = currying2(fn2); // let res2 = add2(1)(2,3,9,9)()Copy the code

The application of coriolization functions

  • So with that out of the way, let’s see how this function works in a real program

Parameter reuse/delay running

  • You can pass a specified argument in advance, pass the return function (which can then be reused) another argument,
  • At the same time, this function also achieves the purpose of lazy execution
  • Bind also uses the idea of currying functions
Function check(reg, TXT) {return reg. Test (TXT)} check(/\d+/g, 'test') //false check(/[a-z]+/g, 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 hasLetter('21212') // falseCopy the code