Skip to content

Instantly share code, notes, and snippets.

@j0lvera
Created September 19, 2013 20:58
Show Gist options
  • Save j0lvera/6629741 to your computer and use it in GitHub Desktop.
Save j0lvera/6629741 to your computer and use it in GitHub Desktop.
var curry = (function () {
var makeFn = function (fn, arity, reverse, prevArgs) {
return function () {
var newArgs = Array.prototype.slice.call(arguments, 0),
args = prevArgs.concat(newArgs);
if (args.length < arity) {
return makeFn(fn, arity, reverse, args);
} else {
return fn.apply(null, reverse ? args.reverse() : args);
}
};
};
return function (fn, arity, reverse) {
if (typeof arity === "undefined") {
arity = fn.length;
}
return makeFn(fn, arity, reverse, []);
};
}).call(null);
Function.prototype.c = function (arity, reverse) {
return curry(this, arity, reverse);
};
// Examples
var foo = function (a, b, c) { return a + b + c }.c();
foo(1)()(1, 1) // => 3
foo(2)(2)(2) // => 6
foo()()()()(1) // => [Function]
// first parameter overrides the function arity (number of parameters)
var max3 = Math.max.c(3);
max3(1, 2, 3) // => 3
max3(1)(3)(10) // => 10
// second parameter reverses the parameters before applying
var delay = setTimeout.c(2, true)(1000);
delay(function () {
console.log("this will run after 1 second");
});
// curry is basically a better way of doing what Function.prototype.bind does
var add = function (x, y) { return x + y; };
var add10 = add.bind(null, 10);
add10(20) // => 30
// same thing with currying
var add = function (x, y) { return x + y }.c();
var add10 = add(10);
add10(40) // => 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment