How to avoid multiple variable re-declarations on function outputs in JavaScript

前端 未结 6 1299
生来不讨喜
生来不讨喜 2021-01-24 16:37

Consider the following example

function doSomethingToAVariable(variable){
    return variable + 1
}

function doSomethingToAVariableASecondTime(variable){
    re         


        
6条回答
  •  滥情空心
    2021-01-24 17:30

    In my humble opinion, your code is perfectly fine.

    But, you can do something like this if you really want to "chain" the calls. It is a bit less efficient though.

    function chainCalls(initVal, funcs){
      return funcs.reduce(function(val, f){
        return f(val);
      }, initVal || 0);
    }
    
    function doSomethingToAVariable(variable){
        return variable + 1
    }
    
    function doSomethingToAVariableASecondTime(variable){
        return variable + 2
    }
    
    function doSomethingToAVariableLastly(variable){
        return variable + 3
    }
    
    var myVariable = chainCalls(0, [doSomethingToAVariable,
                                    doSomethingToAVariableASecondTime,
                                    doSomethingToAVariableLastly]);
    
    document.write(myVariable);

    Another alternative is to create a reusable function chain like this.

    function functionChain(){
      var funcs = arguments;
      return function(value){
        return Array.prototype.reduce.call(funcs, function(value, f){
          return f(value);
        }, value);
      };
    }
    
    function doSomethingToAVariable(variable){
        return variable + 1
    }
    
    function doSomethingToAVariableASecondTime(variable){
        return variable + 2
    }
    
    function doSomethingToAVariableLastly(variable){
        return variable + 3
    }
    
    var myVariable = functionChain(
      doSomethingToAVariable,
      doSomethingToAVariableASecondTime,
      doSomethingToAVariableLastly
    )(0);
    
    document.write(myVariable);

提交回复
热议问题