JavaScript中的函数组合 [英] Function composition in JavaScript

查看:116
本文介绍了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.

推荐答案

首先,阅读起来比较容易。性能很少比这更重要。此外,您可以制作具有几乎相同性能的专用arity 2功能。

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

这允许您在运行时根据用户点击的内容和顺序创建一个组合函数 c

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

这篇关于JavaScript中的函数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆