Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 855
Roman Liutikov Avatar asked Apr 25 '26 08:04

Roman Liutikov


1 Answers

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.

like image 70
Karl Bielefeldt Avatar answered Apr 27 '26 00:04

Karl Bielefeldt