Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active July 20, 2016 15:10
Show Gist options
  • Save kavitshah8/0830b173a510fcd495441033db4db015 to your computer and use it in GitHub Desktop.
Save kavitshah8/0830b173a510fcd495441033db4db015 to your computer and use it in GitHub Desktop.
Currying
function realSum(a, b) {
return a + b;
};
console.log(realSum(5, 3)); // 8
var sum5 = curryIt(realSum, 5);
console.log(sum5(4)); // 9
var sum3 = curryIt(realSum, 3);
console.log(sum3(4)); // 7
function realSum(a, b) {
return a + b;
};
function sum(a, b) {
return b ?
realSum(a, b) :
function(b) {
// This anonymous function has access to variable `a` via closure
return realSum(a, b);
}
}
console.log(sum(5, 3)); // 8
var sum5 = sum(5);
console.log(sum5(4)); // 9
var sum3 = sum(3);
console.log(sum3(4)); // 7
var curryIt = function(fn) {
var fnArgsWhileBeingCurried = Array.prototype.slice.call(arguments, 1);
return function() {
var fnArgsAfterBeingCurried = Array.prototype.slice.call(arguments, 0);
return fn.apply(this, fnArgsWhileBeingCurried.concat(fnArgsAfterBeingCurried));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment