函数柯里化的两种写法

  • A+
所属分类:ES6 javascript JS框架

'use strict';
var arr = [];

for( let i = 0; i < 5; i++){
	arr[i] = function( next ){
		this.num++;
		next();
	}
}

function chkArr( arr ){
	if( !Array.isArray( arr ) ) return 'paramter must be an array!';
	for( let item of arr ){
		if( typeof item !== 'function' ) return 'paramter must be composed of function';
	}
	return false;
}

function curry$1( arr ){
	let ref = chkArr( arr );
	if( ref ) return Promise.reject( ref );
	return function( context, next ){
		var i = -1;
		return dispatch(0);
		function dispatch( num ){
			if( num <= i ) return Promise.reject('error');
			i = num;
			let fn = arr[i];
			if( num === arr.length ) fn = next;
			if( !fn ) return Promise.resolve( context );
			try{
				fn.call(context, function next(){
					return dispatch(i + 1)
				})
				return Promise.resolve( context );
			}catch(e){
				return Promise.reject(e)
			}
		}
	}
}

function curry$1( arr ){
	let ref = chkArr( arr );
	if( ref ) return Promise.reject( ref );
	return function( context, next ){
		try{
			arr.reduceRight( ( pre, cur ) => {
				return cur.bind( context, pre )
			}, next ).call( context )
		}catch(e){
			return Promise.reject(e)
		}
		return Promise.resolve( context )
	}
}

curry$1( arr )( {num: 0}, () => {console.log("over!")} ).then( (context) => { console.log(context.num) } )
weinxin
我的微信
欢迎来撩!!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: