Underscore.js: how to chain custom functions

前端 未结 7 1397
南方客
南方客 2020-12-31 01:11

Using Underscore.js, I can write the following which returns 42:

_([42, 43]).chain()
    .first()
    .value()

I have custom f

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 01:49

    Using compose is another way dealing with the situation, but I think adding a function such as take as I suggested earlier is a better solution. Still, here is how the code would look like with compose:

    function double(value) { return value * 2; };
    
    _.compose(
        double,
        _.first,
        _.bind(_.identity, _, [42, 43])
    )();
    

    The initial value needs to be provided through a function which returns that value (here done by currying identity), and the functions need to be listed in an other which is the reverse of what you have with a chain, which appears as pretty unnatural to me.

提交回复
热议问题