3

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.

3
  • 3
    It is concise. If you're so much tightly bounded by performance - you would prefer speed over "readability" anyway. Commented Mar 3, 2015 at 0:11
  • I don't see how you can compare the two... Commented Mar 3, 2015 at 0:13
  • 1
    c produces the same result for every (?) input. Why do you think it's not comparable? Commented Mar 3, 2015 at 0:14

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What do you mean by "composition can be easily changed at runtime"?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.