Function composition in JavaScript

What's the benefit of function composition implementation in libs like underscore, lo-dash and others, similar to this one:

var compose = function() {
    var funcs = arguments;

    return function() {
        var args = arguments;
        for (var i = funcs.length; i --> 0;) {
            args = [funcs[i].apply(this, args)];
        }
        return args[0];
    }
};

var c = compose(trim, capitalize);

in comparison to this:

var c = function (x) { return capitalize(trim(x)); };

The latter is much more performant.

Answers:

Answer

For one, it's easier to read. Performance is rarely more important than that. Also, you could make a dedicated arity 2 function with nearly the same performance.

The other benefit is the composition can be easily changed at runtime. You can create versions that trim before capitalization, capitalize before trimming, trim only, capitalize only, or neither, without having to explicitly specify every single combination in the code. This can greatly simplify your code sometimes. Runtime composition is one of those things you never knew you always wanted.

For example:

var c = function(x) {return x;} // identity
var onTrimClick          = function() {c = compose(c, trim);}
var onCapitalizeClick    = function() {c = compose(c, capitalize);}
var onSomethingElseClick = function() {c = compose(c, somethingElse);}

This lets you create a composed function c at runtime based on what the user clicks and in what order.

Answer

//A simple way to understand javascript function composition =>

function composition(...fun) {
    return function (value) {
        var functionList = fun.slice();
        while (functionList.length > 0) {
            value = functionList.pop()(value);
        }
        return value;
    }
}

function mult2(value) {
    return value * 2;
}

function mult3(value) {
    return value * 3;
}

function mult5(value) {
    return value * 5;
}

var composedFun = composition(mult2, mult3, mult5);
console.log(composedFun);
console.log(composedFun(1));
console.log(composedFun(2));

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.