Rutwick Gangurde - 8 months ago 46

Javascript Question

This was an interview question which I haven't yet been able to figure out. Consider the following:

`function recurse(a) {`

return function(b) {

console.log(a + b);

}

}

//This will log '5' in the console

recurse(2)(3);

Now I was asked to write a function that will take

`n`

`//This should log '13'`

recurse(2)(3)(1)(7)

How can such a function be written? I have tried thinking over it in terms of recursion, dynamic arguments etc. But haven't been able to write down anything concrete.

Answer

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);
```

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.