How to chain functions without using prototype?

前端 未结 4 909
既然无缘
既然无缘 2020-12-08 21:42

I have a bunch of useful functions that I have collected during my whole life.

function one(num){
    return num+1;
}

function two(num){
    return num+2;
}         


        
4条回答
  •  执念已碎
    2020-12-08 22:47

    Another alternative is to use lodash flow function. For example:

    var five = _.flow(one, two, two)
    five(5)
    

    I prefer assigning a new chain to a variable. It gives it a clear name and encourages re-use.

    Btw, lodash also helps in passing additional arguments to the functions of the chain. For example:

    var addFive = _.flow(
       _.partialRight(_.add, 1),
       _.partialRight(_.add, 2),
       _.partialRight(_.add, 2)
    )
    

    There are many other useful functions to help in functional chaining, e.g., partial, spread, flip, negate, etc.

提交回复
热议问题