sum(a)(b)(c).....(n)

Medium ImportantDEShaw

Prompt

Implement a function sum that allows you to add a sequence of numbers by calling the function multiple times. The function should return another function that takes the next number as an argument. When the final number is provided, the sum of all numbers should be returned.

sum(1)(2)(3)(); // Returns 6
sum(5)(-1)(2)(4)(); // Returns 10

Playground

Hint

Think about how you can use closures to maintain the state of the sum across multiple function calls. Each function call should return another function that either updates the sum with the next number or returns the final sum.

Hint
  • The sum function should return another function.
  • This inner function checks if a number is provided.
  • If a number is provided, it calls the sum function again with the current sum plus the new number.
  • If no number is provided, it returns the current sum.

Solution

Explanation

sum(2)(3)( );

  • sum(2) returns an inner function
  • That inner function is called with (3)
  • Inside the inner function, it sees that b (3) is truthy
  • It calls sum(2 + 3) recursively, which returns another inner function
  • That inner function is called with no argument ( )
  • Inside the inner function, it sees that b is falsy (undefined)
  • It returns a, which is 5

sum(2)(3)(5)( );

  • sum(2) returns an inner function
  • That inner function is called with (3)
  • Inside the inner function, it sees that b (3) is truthy
  • It calls sum(2 + 3) recursively, which returns another inner function
  • That inner function is called with (5)
  • Inside the inner function, it sees that b (5) is truthy
  • It calls sum(5 + 5) recursively, which returns another inner function
  • That inner function is called with no argument ( )
  • Inside the inner function, it sees that b is falsy (undefined)
  • It returns a, which is 10
00:00