Underscore.js: how to chain custom functions

前端 未结 7 1396
南方客
南方客 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条回答
  •  旧时难觅i
    2020-12-31 01:59

    Not finding a tap that returns the value returns by the function is runs, I define one which I can take and add to _:

    _.mixin({take: function(obj, interceptor) {
        return interceptor(obj);
    }});
    

    Then assuming I have:

    function double(value) { return value * 2; };
    

    I can write:

    _([42, 43]).chain()
        .first()             // 42
        .take(double)        // Applies double to 42
        .value()             // 84
    

    You can look at take as map on objects, instead of lists. Want to experiment with this? See this example on jsFiddle.

提交回复
热议问题