Variadic curried sum function

Solution 1:

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

Solution 2:

This is an example of using empty brackets in the last call as a close key (from my last interview):

sum(1)(4)(66)(35)(0)()

function sum(numberOne) {
  var count = numberOne;
  return function by(numberTwo) {
    if (numberTwo === undefined) {
      return count;
    } else {
      count += numberTwo;
      return by;
    }
  }
}
console.log(sum(1)(4)(66)(35)(0)());

Solution 3:

I'm posting this revision as its own post since I apparently don't have enough reputation yet to just leave it as a comment. This is a revision of @Rafael 's excellent solution.

function sum (n) {
    var v = x => sum (n + x);
    v.valueOf = () => n; 
    return v;
}

console.log( +sum(1)(2)(3)(4) ); //10

I didn't see a reason to keep the v.toString bit, as it didn't seem necessary. If I erred in doing so, please let me know in the comments why v.toString is required (it passed my tests fine without it). Converted the rest of the anonymous functions to arrow functions for ease of reading.

Solution 4:

Here is a solution that uses ES6 and toString, similar to @Vemba

function add(a) {
  let curry = (b) => {
    a += b
    return curry
  }
  curry.toString = () => a
  return curry
}

console.log(add(1))
console.log(add(1)(2))
console.log(add(1)(2)(3))
console.log(add(1)(2)(3)(4))

Solution 5:

New ES6 way and is concise.

You have to pass empty () at the end when you want to terminate the call and get the final value.

const sum= x => y => (y !== undefined) ? sum(x + y) : x;

call it like this -

sum(10)(30)(45)();