Add function

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.

Example

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
const adder = add(1)
adder + 1 == 2
adder(2) == 3Code language: JavaScript (javascript)

I’m not sure how you would do it in other languages but in javascript, the solution is 3 lines long but takes a second to wrap your head around. This actually took me a while to figure out so I’m pretty bummed it was so short.

The Code

function add(a) {
    const adder = b => add(a + b)
    adder.valueOf = () => a
    return adder
}
Code language: JavaScript (javascript)

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:

Recursion

Michael | MMusangeya

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.

Higher-Order Functions

Basically functions that use and operate on other functions. They can receive functions as arguments and return functions as values.

Function Representation

This is not the official term but I like it so I’m using it. Since functions are treated like any other object in javascript you can change how they are represented. You can override either the 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.

Conclusion

This problem looks simple but it exercised my JavaScript knowledge. It reminded me that there is still so much I don’t know and renewed my drive to master this weird weird language.

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.