Today we have a quirky problem that requires knowledge of higher-order functions, recursion, and advanced language features. It’s an add function that returns an adder function.
Add Function Problem
The problem is to create a function that will add numbers together when called in succession.
add(1)(2) == 3
It should chain as many times as we want so
add(1)(1)(1)(1) == 4
But wait, there’s more!
If called once it should return the adder function and also be equal to the number given. So;
add(1) == 1
So we create an adder function that calls the calling functions with the sum then we change how that adder function is represented using valueOf.
Three concepts in three lines.
I won’t go into greater detail here but in short:
In summary, defining a problem in terms of itself. I.e. when you have a function that calls itself. I won’t go into it here, but it’s an advanced programming technique that makes it very easy to fill up your memory.
Basically functions that use and operate on other functions. They can receive functions as arguments and return functions as values.
valueOf or the
toString methods to achieve this.
In normal everyday programming, you don’t really use this feature but it’s there because reasons.
If you have another solution perhaps in another language please feel free to share it. You can contact me on Twitter @phoexer and as always happy coding.