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.

2
  • 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 Commented Oct 27, 2020 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. Commented Oct 28, 2020 at 0:14

1 Answer 1

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;
}

Sign up to request clarification or add additional context in comments.

4 Comments

Please mark the question as accepted if it helped you :)
This is basically my code. What did you add?!
The comments explaining how it works and why you need that last call to be with empty parenthesis :)
Please mark my answer as accepted if it helped you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.