Created
December 2, 2011 12:50
-
-
Save jaseemabid/1423128 to your computer and use it in GitHub Desktop.
JavaScript Currying.
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
/* | |
* Curried code to add multiple numbers | |
Author : Jaseem Abid <[email protected]> | |
* sum() expects 2 numbers are arguments | |
* If 2 args are provided, it returns sum as usual. | |
* If one arg is provided, it returns a | |
function which expects one more arg. JS closures can | |
'remember the first argument' and work accordingly. | |
* If no arguments are supplied, it returns itself. | |
*/ | |
sum = function sum(a,b) { | |
if (arguments.length < 1) { | |
return sum; | |
} else if (arguments.length < 2) { | |
return function(c) { | |
return c + a; | |
} | |
} else return a+b; | |
}; | |
/* | |
All calls give the same expected result, 5 | |
*/ | |
console.log( sum(2,3) ); | |
console.log( sum(2)(3) ); | |
console.log( sum()()(2)(3) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment