Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function return function javascript

Tags:

javascript

I have a simple demo:

function add(a) {
    return function (b) {
        return a + b
    }
}

Now when I call add(1)(2) it will give me 3

but I want something like this:

add(1)(2)(3) -> 6

add(1)(2)(3)(4) -> 10

it means I can add more function if I want. How to write it?

like image 738
Khuong Avatar asked Mar 06 '23 13:03

Khuong


1 Answers

I have seen a similar problem elsewhere, but there the requirement was slightly different. Instead of having add(1)(2)(3) return 6, it was required to have add(1)(2)(3)() return 6.

Notice that the last invocation of the function does not have any arguments. This is important distinction because the function should either return another function that taken in a number as an argument or it should return the total of the arguments passed so far. Without the distinction of the last parameter being undefined (or NaN) it is not possible to decide whether to return a currying function or the total so far.


So I will assume that what you want is to have add(1)(2)(3)() return 6. Here's how you could do that:

  • As already explained, the add function either returns another function that takes an argument if the current parameter is a number.

  • If the current argument is undefined (or NaN) it returns the sum.

  • You keep track of the sum using a variable sum that is available to the total function through closure.

function add(x) {
  var sum = x;
  return function total(y) {
    if (!isNaN(y)) {  
      sum += y;
      return total;
    } else {
      return sum;
    }
  }
}

console.log(add(5)(2)());
console.log(add(5)(3)());
console.log(add(1)(2)(3)(4)());
like image 134
Nisarg Shah Avatar answered Mar 15 '23 18:03

Nisarg Shah