How to chain functions without using prototype?

前端 未结 4 921
既然无缘
既然无缘 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:39

    A nice and general alternative is creating a custom function composition function

    var go = function(x, fs){
       for(var i=0; i < fs.length; i++){
           x = fs[i](x);
       }
       return x;
    }
    

    You can call it like this:

    go(5, [one, two, two])
    

    I am personaly not a big fan of method chaining since it restricts you to a predefined set of functions and there is kind of an impedance mismatch between values inside the "chaining object" and free values outside.

提交回复
热议问题