Chapter 2 - partial applications

by Denise Nepraunig

HTML

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>

JavaScript

// 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) */