Skip to content

Instantly share code, notes, and snippets.

@jaseemabid
Created December 2, 2011 12:50
Show Gist options
  • Save jaseemabid/1423128 to your computer and use it in GitHub Desktop.
Save jaseemabid/1423128 to your computer and use it in GitHub Desktop.
JavaScript Currying.
/*
* 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