Function.prototype.curry = function () {
var fn = this, args = Array.prototype.slice.call(arguments);
return function () {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
Coming from a backend technology (ie. Java), I was a little baffled by this at first. After all, I thought I knew a thing or two about javascript. Howeveer, the first task was to try to invoke the above function so I can trace the steps to gain a better understanding. The first thing I did was to think of an scenario to call this:
console.log(Math.min.curry('1', '2')('3')); // == 1
Seemed a little unnatural, but sure I can live with that.
Once I figured that out, the next step was to see what the arguments parameters was. You'd think that they were the same, but unfortunately I forgot the fact that it was returning a new function, that means the context of `this` changes (which I knew) AND that the arguments list also changed. Once I figured that out then the rest came easy.
The lesson of the day is: look for places where it's returning a new function...the contexts (this and arguments) will most likely change!
No comments:
Post a Comment