Currying in JavaScript and Groovy
[
posted in
Programming
]
def c = { arg1, arg2-> println "${arg1} ${arg2}" }
def d = c.curry("foo")
d("bar")
Basically, you bind one argument to a function taking multiple arguments but don't call the function until the remaining arguments are passed in.
function sum(a, b) {
return a + b;
}
sum(10, 5) // 15
var addTen = sum.curry(10);
addTen(5) // 15
If you don't want to adopt prototype, you can use the following implementation:
function curry(f, args) {
var thisF = f;
var thisArgs = Array.prototype.slice.apply(args);
return function(args) {
thisArgs = thisArgs.concat(args);
if (thisF.length <= thisArgs.length) {
return thisF.apply(thisF, thisArgs);
} else {
return this;
}
}
}
With the canonical summation test:
function sum(a, b, c) {
return a + b + c;
}
function test() {
sum(1, 2, 3); // 6
x = curry(sum, [1]);
x([2]);
x([3]); // 6
x = curry(sum, [1]);
x([2, 3]); // 6
}
This has not been put through a lot of testing, so YMMV. After looking at the other examples provided in the blogs above, I was astounded how little code it took me to write. As I test more and across multiple browsers, I'm sure it will start bloating...
[
posted on 30 October 2007 at 11:07:30 AM
]