javascriptcurrying

Variadic curried sum function


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 that if adding + in front of sum can be done. Like +sum(1)(2)(3)(4).
Any ideas of how to do this?


Solution

  • Not sure if I understood what you want, but

    function sum(n) {
      var v = function(x) {
        return sum(n + x);
      };
    
      v.valueOf = v.toString = function() {
        return n;
      };
    
      return v;
    }
    
    console.log(+sum(1)(2)(3)(4));

    JsFiddle