js实现扁平化思想
function compose ( ... funcs) {
return function proxy ( ... args) {
let len = funcs. length;
if ( len === 0 ) {
return args;
} else if ( len === 1 ) {
return funcs[ 0 ] ( ... args) ;
} else {
return funcs. reduce ( ( x, y) => {
return typeof x === "function" ? y ( x ( ... args) ) : y ( x)
} ) ;
}
}
}
let fn1 = function ( x) {
return x + 10 ;
} ;
let fn2 = function ( x) {
return x * 10 ;
} ;
let fn3 = function ( x) {
return x / 10 ;
} ;
console. log ( compose ( ) ( 5 ) ) ;
console. log ( compose ( fn1) ( 5 ) ) ;
console. log ( compose ( fn1, fn2) ( 5 ) ) ;
console. log ( compose ( fn1, fn2, fn1, fn3) ( 5 ) ) ;
function compose ( ... funcs) {
if ( funcs. length=== 0 ) {
return arg=> arg;
}
if ( funcs. length=== 1 ) {
return funcs[ 0 ] ;
}
return funcs. reduce ( ( a, b) => ( ... args) => a ( b ( ... args) ) ) ;
}
console. log ( compose ( ) ( 5 ) ) ;
console. log ( compose ( fn1) ( 5 ) ) ;
console. log ( compose ( fn1, fn2) ( 5 ) ) ;
console. log ( compose ( fn1, fn2, fn1, fn3) ( 5 ) ) ;