Last active
August 29, 2015 14:14
-
-
Save kevincennis/9714ca4d16db1bd39c31 to your computer and use it in GitHub Desktop.
curry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function.prototype.curry = function curry() { | |
var fn = this, | |
arity = fn.length, | |
slice = Array.prototype.slice, | |
args = slice.call( arguments ); | |
function accumulator() { | |
var locArgs = args; | |
if ( arguments.length > 0 ) { | |
locArgs = locArgs.concat( slice.call( arguments ) ); | |
} | |
if ( locArgs.length >= arity ) { | |
return fn.apply( null, locArgs ); | |
} else { | |
return curry.apply( fn, locArgs ); | |
} | |
} | |
return args.length >= arity ? accumulator() : accumulator; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function add3nums( a, b, c ) { | |
return a + b + c; | |
} | |
var curried = add3nums.curry(); | |
curried( 3 )( 4 )( 5 ); // 12 | |
curried( 3, 4 )( 5 ); // 12 | |
curried( 3 )( 4, 5 ); // 12 | |
curried()( 3 )()( 4 )()( 5 ); // 12 | |
curried( 3, 4, 5 ); // 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment