“add” function that works with different combinations of chaining/arguments

前端 未结 4 1849
忘掉有多难
忘掉有多难 2020-11-28 13:09

I\'m trying to write an add function that will work in many scenarios.

add(2,2,2) //6
add(2,2,2,2) //8
add(2)(2)(2) // 6
add(2)(2)(2,2).value() //8
add(2,2)(         


        
4条回答
  •  时光取名叫无心
    2020-11-28 13:19

    Since you are returning the sum in the ret.add function thats why the error is coming try something like this, hope it will solve your problem

    function add(){
        var sum = 0;
        for( var i in arguments ){
            sum += arguments[i];
        }
    
        var ret = add.bind(null, sum);
    
        ret.value = function () {
          return sum;
        }
    
        ret.add = function () {
          for( var i in arguments ){
            sum += arguments[i];
          }
          return ret;
        }
    
        ret.valueOf = function(){ return sum; };
    
        return ret;
    }
    

提交回复
热议问题