函数柯西化(经典面试题)
add ( 1 ) ( 2 ) ( 3 ) = 6 ;
add ( 1 , 2 , 3 ) ( 4 ) = 10 ;
add ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) = 15 ; function add ( ) { var _args = Array . prototype. slice . call ( arguments) ; var _adder = function ( ) { _args. push ( ... arguments) ; return _adder; } ; _adder. toString = function ( ) { return _args. reduce ( function ( a, b ) { return a + b; } ) ; } return _adder;
} add ( 1 ) ( 2 ) ( 3 )
add ( 1 , 2 , 3 ) ( 4 )
add ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 )
add ( 2 , 6 ) ( 1 )
加强理解版本
function curry ( fn, ... args ) { return function ( ) { return fn . apply ( this , args. concat ( [ ] . slice . call ( arguments) ) ) ; }
}
function add ( a, b ) { return a + b;
} var addCurry = curry ( add, 1 , 2 ) ;
console. log ( addCurry ( ) ) ;
var addCurry = curry ( add, 1 ) ;
console. log ( addCurry ( 2 ) ) ;
var addCurry = curry ( add) ;
console. log ( addCurry ( 1 , 2 ) ) ;
function sub_curry ( fn ) { let args = [ ] . slice . call ( arguments, 1 ) ; return function ( ) { return fn . apply ( this , args. concat ( [ ] . slice . call ( arguments) ) ) ; }
} function curry ( fn, length ) { length = length || fn. length; let slice = Array . prototype. slice; return function ( ) { }
}
function curryFn ( fn, args ) { let length = fn. length; args = args || [ ] ; return function ( ) { let _args = args. slice ( 0 ) ; for ( let i = 0 ; i < arguments. length; i++ ) { _args. push ( arguments[ i] ) ; } if ( _args. length < length) { return curryFn . call ( this , fn, _args) ; } else { return fn . apply ( this , _args) ; } }
} let fn = curryFn ( function ( a, b, c ) { console. log ( [ a, b, c] ) ;
} ) ; fn ( "a" , "b" , "c" )
fn ( "a" , "b" ) ( "c" )
fn ( "a" ) ( "b" ) ( "c" )
fn ( "a" ) ( "b" , "c" )