Variadic curried sum function

前端 未结 16 1851
清酒与你
清酒与你 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:23

    let add = (a) => {
      let sum = a;
      funct = function(b) {
        sum += b;
        return funct;
      };
    
      Object.defineProperty(funct, 'valueOf', {
        value: function() {
          return sum;
        }
      });
      return funct;
    };
    
    
    console.log(+add(1)(2)(3))
    

提交回复
热议问题