Here's the simplest version I could think of:
function add (a) {
return function (b) {
return b == null ? a : add(a+b);
}
}
console.log(
add(2)(3)()
);
console.log(
add(10)(100)(1000)(4)()
);
In es6, it's compact!
let add = a => b => b == null ? a : add(a+b);
Note
The trouble with your question is that a function can either return a Function
or a Number
. The following code:
let result = add(2)(3);
is equivalent to:
/*1*/ let partialResult = add(2);
/*2*/ let result = partialResult(3);
In line 1, add
doesn't know whether it is being called with the last argument or not! In other words, it doesn't know whether partialResult
should be a number, or a function that will be called with another argument.
Nina Scholz gives you a solution where partialResult
will behave like a number when treated like a primitive, and like a function when called like a function. In my solution, partialResult
always acts like a function, and returns a sum when called without an argument.
The first approach requires a language-specific mechanism for "behaving like a number" under certain conditions. If your interview was about JavaScript, it's the best approximation! But in a language-agnostic context, what you are asking for is impossible.