javascript - partial application

javascript partial application, composition, flipping

by deshpandeakhil

HTML

<div id="output"/>

CSS

div {margin:10px;}

JavaScript

// partial application 
// is a way by which we can take a function and bind it against one or more parameters to create a new function
var op = $("#output");
op.append("Partial Application" + "<br/>");
Function.prototype.parApp = function() {
    // capture the bound arguments
    var args = Array.prototype.slice.call(arguments);
    op.append("args: " + args + "<br/>");
    var f = this;
    // construct a new function
    return function() {
        // prepend argument list with the closed arguments from above
        var inner_args = Array.prototype.slice.call(arguments);
        op.append("inner_args: " + inner_args + "<br/>");
        return f.apply(this, args.concat(inner_args))
    };
};

var add = function(x, y) {
    return x + y;
}
var add10 = add.parApp(10);
op.append(add10(5));

// composition
// composition is an operation that prduces a new function by nesting two functions
// z(x) = f(g(x))
op.append("<br/><br/>Composition<br/>");
Function.prototype.compo = function(g) {
    var f = this;
    return function() {
        var args = Array.prototype.slice.call(arguments);
        return f.call(this, g.apply(this, args));
    };
};
var format1 = function(s) {
    return "------------ " + s + " --------------";
};
var format2 = function(s) {
    return "<< " + s + " >>";
};
var printWithFormat = format1.compo(format2);
op.append(printWithFormat("Some Text"));

// flipping 
// convert function f(a,b) to g(b,a)
var div = function(a, b) {
    return a / b;
};
op.append("<br/><br/>Flipping<br/>");
Function.prototype.flip = function() {
    var f = this;
    return function() {
        var args = Array.prototype.slice.call(arguments);
        return f.apply(this, args.reverse());
    };
};
op.append(div(4, 2) + "<br/>");
op.append(div.flip()(4, 2) + "<br/>");