I'm currently working on a programming problem in my personal time that asks that I make a javascript function that can be called in this manner.
add(1) // 1
add(1)(2) // 3
add(1)(2)(3); // 6
add(1)(2)(3)(4); // 10
add(1)(2)(3)(4)(5); // 15
What I'm having trouble figuring out is how to make it return a value on the very last call.
For example, in order for add(1)(2)
to work, then add(1)
has to return a function, but according to the instructions add(1)
when called by itself will return 1
.
I'm assuming one way you can overcome this is to figure out how many times in succession the add
function is being called, but I cannot think of a way to achieve that. Does anyone have any hints that can point me in the right direction?
I've read these two articles (1, 2) on function currying and I understand them, but I'm not sure how to do currying when dealing with a variable number of arguments.