Analysis on Coriolization of JavaScript Function

  • 2021-08-12 01:55:40
  • OfStack

Currization (Currying) transforms an original function that receives multiple parameters into a function that accepts a single parameter (the first parameter of the original function) and returns a new function. The new function can accept the remaining parameters and return the same result as the original function.

The way of ES6 to realize the universality of Coriolization


function currying(fn,...rest1){
	return function(...rest2){
		// Used here apply  Is to pass the parameters in array form directly into the original function  null Because there is no need to change this
		return fn.apply(null,rest1.concat(rest2));
	}
}

Curritization of an sayHello function


function sayHello(name,age,fruit){
	console.log(` My name is ${name}, I ${age} I like to eat. I'm 20 years old ${fruit}`);
}

// Afferent number 1 Parameters 
let curryingShowMsg = currying(sayHello,' Xiao Ming ');
// Execute the remaining parameters passed in 
curryingShowMsg(22,' Mango ');

Anti-Corrigenization is just the opposite of Corrigenization. In order to make the method usage scenario wider, anti-Currization can be used to lend out the native method and let any object have the method of the native object.

The difference between two


// Currification 
//function(arg1,arg2) => function(arg1)(arg2);
//function(arg1,arg2,...,argn) => function(arg1)(arg2)(...)(argn)
// Anti-Currization 
//obj.func(arg1,arg2) => func(obj,arg1,arg2)

ES6 Realizes 1 Anti-Corritization


function unCurrying(fn){
	//tar  It's the object we lend to   Previously needed xxx.fn(xx)  You can do it now fn(xxx,xx)
	return function(tar,...argu){
		return fn.apply(tar,argu);
	}
}
// For example, we want to put Array.prototype.push Method borrowed from native 
let push = unCurrying(Array.prototype.push);
//arrguments It's the object we lend to 
push(arguments,4);

High-order implementation of function Corritization, the above function only implements one layer of simple Corritization. If we realize complete Corritization func (xx) (xx) (xx) (xx), we have to nest our Corritization function repeatedly. Here we implement a higher-order general method of Corritization.


function curryingHelper(fn,len){
	// Let's talk about a basic knowledge point first  fn.length  Returns the number of parameters that this method needs to pass in 
	// Here the first 1 The second runtime passes through fn.length  The recursion behind is all passed in by len len Is the number of remaining parameters 
	const length = len || fn.length;
	return function(...rest){
		// Determine whether the parameter passed in this time is greater than or equal to the remaining parameters   If it is not recursively returned under 1 Methods continue to pass parameters 
		return rest.length >= length 
		? fn.apply(this,rest)
		: curryingHelper(currying.apply(this,[fn].concat(rest)),length-rest.length)
	}
}
// Or just now sayHello  Function 
let betterShowMsg = curryingHelper(sayHello);
// Automatic control of parameter transmission layers 
betterShowMsg('zyx')(22)(' Grapes ');
betterShowMsg('zyx',22)(' Grapes ');

Three Uses of Currification

1 parameter multiplexing


function Say(name,some){
	console.log(name + ' Say ' + some);
}
// What if we just want zyx Say 1 Something 
let zyxSay = currying(Say,'zyx');
zyxSay('1111');//zyx Say 1111

2 Improve applicability


// Generic functions solve the compatibility problem, but at the same time, in different scenarios, we may be the same as 1 This kind of rule needs to be used repeatedly 
// This may cause code repetition   For example 

function square(i){ return i*i }// Square 
function dubble(i){ return i*2 }// Double 
function map(handler,list){
	//handle  Is the rule of operation  list Is operational arrguments
	return list.map(handler)
}

map(square,[1,2,3]);// Array per 1 Term square 
map(dubble,[1,2,3]);// Array per 1 Term doubling 
// This is universality   I can use the same 1 Functions do many different operations 
// But if we need to do a lot of square operations,   Every time we need to pass in the method and then pass in the array, the code is wasted 
// At this time, we improve practicality through Currification 

let mapSQ = currying(map,square);// A new trivial operation function directly defined 
mapSQ([1,2,3]);// You don't have to pass in the operation method in the future 

3 Delayed execution


let add = function(...rest){
	// Definition 1 Closure save _args
	const _args = [];
	return function cb(...rest){
		if(rest.length == 0){
			// If you don't wear parameters,   That is add()  It means that we need to execute the function finally 
			let res = 0;
			// Accumulation 
			console.log(_args);
			for(let data of _args){
				res += data;
			}
			return res;
		}else{
			_args.push(...rest);
			// To lock args  Closure 
			return _args;
		}
	}
}()

add(1);
add(2);
let a = add();
console.log(a);//3

The above is the detailed analysis of JavaScript function Corritization, more information about JavaScript function Corritization, please pay attention to other related articles on this site!


Related articles: