Last Updated: February 25, 2016
·
799
· bezhermoso

Currying Javascript functions

Here is a code-snippet that gives you the ability to curry any given Javascript function:

 Function.prototype.curry = function () {
  var fn = this,
      args = Array.prototype.slice.call(arguments, 0);
  if (fn.length === args.length) {
    return fn.apply(undefined, args);
  }
  return function (arg) {
    return Function.prototype.curry.apply(fn, args.concat([arg]));
  };
};

This allows you to do something like:

var add = function (x, y) { return x + y; };
var add2 = add.curry()(2);
add2(3); // equivalent to add(2, 3) == 5

This will also work for functions with more than 2 arguments, of course:

var f = function (a, b, c, d) { ... };

f(a, b, c, d) == f.curry()(a)(b)(c)(d) == f.curry(a, b)(c)(d);