Search code examples
javascriptfunctionfunction-call

calling a function several times with saving result


I've got a question.

I need to design a function add() which would sum up given arguments. The problem is that it should be able to be called in several ways as follows:

add(1, 2, 3, 4, 5) // outputs 15
add(1, 2)(3)(4, 5) // outputs 15
add(1, 2, 3)(4, 5) // outputs 15

if the inner part of the function is not a problem and can be implemented like:

return arg.reduce((prev, current) => prev + current)

The number of arguments is always 5. No more, no less.

However, I am not sure how to deal with consecutive calls here. Does anyone have any ideas?

Thanks a lot.


Solution

  • Have add return a function that has a persistent array in its scope, that keeps track of all arguments that have been passed in, cumulatively. On each call, push to that array - once that array has 5 items, return the summed array as a number, otherwise, return the same function:

    function add(...initialArgs) {
      const allArgs = [];
      function inner(...args) {
        allArgs.push(...args);
        return allArgs.length === 5
         ? allArgs.reduce((a, b) => a + b)
         : inner;
      }
      return inner(...initialArgs)
    }
    
    console.log(add(1, 2, 3, 4, 5)) // outputs 15
    console.log(add(1, 2)(3)(4, 5)) // outputs 15
    console.log(add(1, 2, 3)(4, 5)) // outputs 15

    Of course, this depends on knowing in advance that the total number of arguments will always be exactly 5.