Variadic curried sum function

前端 未结 16 1832
清酒与你
清酒与你 2020-11-22 06:33

I need a js sum function to work like this:

sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10 
etc.

I heard it can\'t be done. But heard

16条回答
  •  长情又很酷
    2020-11-22 07:25

    You can make use of the below function

    function add(num){
       add.sum || (add.sum = 0) // make sure add.sum exists if not assign it to 0
       add.sum += num; // increment it
       return add.toString = add.valueOf = function(){ 
          var rtn = add.sum; // we save the value
          return add.sum = 0, rtn // return it before we reset add.sum to 0
       }, add; // return the function
    }
    

    Since functions are objects, we can add properties to it, which we are resetting when it's been accessed.

提交回复
热议问题