Self-currying JavaScript functions

I’m telling you, this language keeps surprising me. You’ll need Prototype for this one.

Function.prototype.toSelfCurrying = function(n) {
  n = n || this.length;
  var method = this;
  return function() {
    if (arguments.length >= n) return method.apply(this, arguments);
    return method.curry.apply(arguments.callee, arguments);
  };
};

Make a simple function:

var adder = function(a,b,c) {
  return a + b + c;
};

And curry away:

var add = adder.toSelfCurrying();

add(1)(2)(3)  // --> 6
add(7,8)(23)  // --> 38

Every call to add returns a curried version of add, until the required number of arguments have been supplied. When all arguments are present, you get a return value.

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.