JavaScript Curry

// Curry

“Currying allows us to produce a new function by combining a function and an argument”

Function.prototype.method = function (name, func) { // makes Augmenting Types beautifully easy when needed
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};

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

Function.method(‘curry’, function () { // leveraging our Augmentation shortcut…
var slice = Array.prototype.slice,
args = slice.apply(arguments),
that = this;

return function () {
return that.apply(null, args.concat(slice.apply(arguments)));
};
});

var add1 = add.curry(1);
document.writeln(add1(6)); //7

 

credit:

Crockford, Douglas. JavaScript: The Good Parts, p.43. O’Reilly 2008

Leave a Reply

You must be logged in to post a comment.