Last Updated: February 25, 2016
·
1.043K
· 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);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside