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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With