Underscore.js: how to chain custom functions

前端 未结 7 1357
南方客
南方客 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 02:11

    Many ways to easily achieve this, here is one such solution:

      _.chain([42,43])
        .first(1)
        .map(double)
        .first()
        .value();
        // 84
    

    However, I would recommend using Ramda then with auto-curry and pipe / compose these kinds of tasks are trivial:

    R.pipe(R.head, R.multiply(2))([42, 43]);  // 84
    
    equivalent to:
    
    R.compose(R.multiply(2), R.head)([42, 43]);  // 84
    

    If you wanted to extend the solution to take say the first 2 items, instead of a single value, as requested by the OP, then:

    R.pipe(R.take(2), R.map(R.multiply(2)))([42, 43])  // [84, 86]
    

    However, in Ramda R.compose is preferred. Either way, for trivial tasks like this, it does tend to be more convenient and easy to use.

提交回复
热议问题