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

前端 未结 4 1850
忘掉有多难
忘掉有多难 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:14

    I have tried to improvise with the use of this. Works for all cases.

    function add(){
        var sum =  this instanceof Number?this: 0;
        for( var i in arguments ){
            sum += arguments[i];
        }
    
        var ret = add.bind(sum);
        ret.add = ret;
        ret.value = ret.valueOf = function() { return sum; };
    
        ret.toString = sum.toString.bind(sum);
    
        return ret;
    }
    

    JS-Fiddle

提交回复
热议问题