// Programming JavaScript Applications
// Chapter 2
// partial application
/* partial application wraps a function that takes multiple arguemnts and retuns a function that takes fewer arguments. It uses closures to 'fix' on ore more arguemtns */
var multiply = function multiply(x, y) {
return x * y;
},
partial = function partial(fn) {
/* arguments
[function multiply(x, y) {
return x * y;
}, 2]
*/
/* just get the arguments, not the function name, so in our case this is [2] */
var args = [].slice.call(arguments, 1);
// return a new function with fixed arguments
return function() {
debugger;
// combine fixed arguments with new arguments and call fn
// with them
// args is still [2] thanks to closures,
// arguments is 4
var combinedArgs = args.concat(
[].slice.call(arguments));
// combined args is now [2, 4]
// fn is the multiply function, thanks to closures
return fn.apply(this, combinedArgs);
}
},
double = partial(multiply, 2);
// after here double is:
/*
function () {
var combinedArgs = args.concat([].slice.call(arguments));
return fn.apply(this, combinedArgs);
}
*/
QUnit.test('Partial application', function(assert) {
assert.equal(double(4), 8, 'partial() works');
});
/* currying would be if whe reduce a complex function to a function which takes only one argument -> multiply(1,2,3) -> multiply(1)(2)(3) */
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.