I`m a newbie at JavaScript trying to understand this tutorial about currying from Oreilly JavaScript Cookbook.
Could someone be kind enough to explain this program in detail step by step in plain language. Please make sure to explain the “null” argument passed in the second last line of the program. Thank you in advance if you can help.
function curry(fn, scope) {
scope = scope || window;
var args = [];
for (var i = 2, len = arguments.length; i < len; ++i) {
args.push(arguments[i]);
}
return function() {
var args2 = [];
for (var i = 0; i < arguments.length; i++) {
args2.push(arguments[i]);
}
var argstotal = args.concat(args2);
return fn.apply(scope, argstotal);
};
}
function diffPoint(x1, y1, x2, y2) {
return [Math.abs(x2 - x1), Math.abs(y2 - y1)];
}
var diffOrigin = curry(diffPoint, null, 3.0, 4.0);
var newPt = diffOrigin(6.42, 8.0); //produces array with 3
In this case the
scopeargument isn’t used at all.scopesets what thethisobject is. The function you are currying doesn’t usethisso it has no real effect. The scope is set whenfn.apply(scope, args)is called, which both sets the scope to run in and provides arguments to pass in.