describe('Step 5', function() {
var curry = function (fn) {
return function () {
var args = [],
accumulate = function accumulate() {
args = args.concat(Array.prototype.slice.call(arguments));
return accumulate;
};
accumulate.value = function () {
return fn.apply(null, args);
};
accumulate.apply(null, arguments);
return accumulate;
};
},
add = curry(function () {
return Array.prototype.reduce.call(arguments, function (total, number) {
return total + number;
}, 0);
});
it('add(2,8)(5).value() => 15', function() {
add(2,8)(5).value()
.should.be.exactly(15).and.be.a.Number;
});
it('add(3, 3, 5)(4)(3, 2).value() => 20', function() {
add(3, 3, 5)(4)(3, 2).value()
.should.be.exactly(20).and.be.a.Number;
});
});
Pass a function fn to curry to create a function that, when called, creates a function that accumulates the arguments passed to it over time, and returns itself. You can apply the accumulated arguments to fn by calling the value method attached to the function returned from the function returned from curry.
In this case you can create an add function which adds up an arbitrary number of arguments, and have that receive the accumulated arguments.
Personally I have never had the opportunity to use this technique. But apparently it's a good interview question, so as for the "how, why and when:" Probably to get hired.