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

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

Consider the following example

function doSomethingToAVariable(variable){
    return variable + 1
}

function doSomethingToAVariableASecondTime(variable){
    re         


        
6条回答
  •  情歌与酒
    2021-01-24 17:27

    If it's as simple as adding some things together how about a recursive method. A bit like using promises but without actually using them.

    function add(x) {
      return {
        done: () => x,
        add: (y) => add(x + y)
      }
    }
    
    let myVariable = 0;
    add(myVariable).add(1).add(2).add(3).done(); // 6
    

    DEMO

提交回复
热议问题