Composing Functions

function composeAll takes arbitrary number of functions as arguments and returns a function that applies the composed functions to the specified values. For added syntactic sugar, we add methods to the function prototype to use the combineAll conveniently.

by Patrick Hund

HTML

<div id="console"></div>

JavaScript

// function composeAll takes arbitrary number of functions as arguments and 
// returns a function that applies the composed functions to the specified values. 
// For added syntactic sugar, we add methods to the function prototype to use 
// the combineAll conveniently.

function add(a, b) {
    return a + b;
}

function mul(a, b) {
    return a * b;
}

function div(a, b) {
    return a / b;
}

function composeAll() {
    var slice = Array.prototype.slice,
        funcs = slice.apply(arguments);
    return function () {
        var value = arguments[0],
            vindex = 1,
            findex;
        for (findex = 0; findex < funcs.length; findex++) {
            value = funcs[findex](value, arguments[vindex++]);
        }
        return value;
    };
}

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

Function.method("and",  function (func) {
    if (this.combined === undefined) {
        this.combined = [this];
    }
    this.combined.push(func);
    return this;
});

Function.method("applyTo", function () {
    var result = composeAll.apply(null, this.combined).apply(null, arguments);
    this.combined = undefined;
    return result;
});

$("#console").append(
    "functions add, mul and div combined and applied to values 1, 2, 3 and 2: " +  
    composeAll(add, mul, div)(1, 2, 3, 2));

$("#console").append("<br>");

$("#console").append(
    "functions add, mul and div combined and applied to values 1, 2, 3 and 2: " +  
    add.and(mul).and(div).applyTo(1, 2, 3, 2));