0

I am stuck with this problem: I want to write a function in javascript named sum that sums the subsequent arguments like this:

sum(1)(2)= 3
sum(1)(2)(3) = 6 
sum(1)(2)(3)(4) = 10, 

and so on. I wrote this code

function sum(a) {
let currentSum = a;

function f() {
    if (arguments.length == 1) {
        currentSum += arguments[arguments.length - 1];
        return f;
    } else {
        return currentSum;
    }

}

f.valueOf = () => currentSum;
f.toString = () => currentSum;

return f;
}

This code works fine if I put empty parentheses at the end of the call like this: sum(1)(2)(3)() = 6 . Is there any way to modify the code so that I can get rid of the empty parentheses?

I appreciate any help. Thanks in advance.

  • 1
    When you use your function in a *math context* it'll automatically call `f.valueOf`, so if you do something like `console.log(0 + sum(1)(2)(3))` it'll return `6`; if it's in a *string context*, it'll use `f.toString` (e.g. `'0' + sum(1)(2)(3)` will return `'06'`); however if there's no particular context, it'll default to a function. You can get rid of the empty parentheses if you do something like `+sum(1)(2)(3)`, but that's probably bad style, since it might create some difficult to debug situations – Steve Oct 27 '20 at 23:28
  • It's impossible to have a value that is both a number and a function. `valueOf` is the best you'll get. – Bergi Oct 28 '20 at 00:14

1 Answers1

1

No, you cannot unfortunately. When you supply a number as an argument, the function sends back another function, so you can run it again. Basically, your code needs 'to know' when you are done adding numbers and want to get a number back:

function sum(a) {
  let currentSum = a;

  function f() {
    // In this case we are adding a number to the sum
    if (arguments.length == 1) {
      currentSum += arguments[arguments.length - 1];
      return f;
      // In this case we are returning the sum
    } else {
      return currentSum;
    }
  }

  f.valueOf = () => currentSum;
  f.toString = () => currentSum;

  return f;
}
IvanD
  • 2,728
  • 14
  • 26