3

I know one way is there any other way to make this type of function call and get the correct addition.

My answer:

function add(x) {

  return function(y) {
  
    return function(z) {
    
      return x + y + z
    }
  }

}

add(4)(5)(6)

It means that the first function returns another function and then that returned function is called immediately then that function returns another function which is then called immediately which will give us the final answer.

Max Vhanamane
  • 163
  • 2
  • 7
Oladipo
  • 1,579
  • 3
  • 17
  • 33
  • 2
    Share your code please – Magicprog.fr Jul 02 '15 at 15:35
  • You should really change your title and improve your narrative... otherwise we just close your question... It's not understandable. – Adrian Salazar Jul 02 '15 at 15:40
  • 4
    Related: [How to correctly curry a function in JavaScript?](http://stackoverflow.com/questions/27996544/how-to-correctly-curry-a-function-in-javascript/30249365) and [Currying with functions that take unlimited arguments](http://stackoverflow.com/questions/20986115/currying-with-functions-that-take-unlimited-arguments) -- but there's probably other questions that are even closer. – apsillers Jul 02 '15 at 15:44
  • Basically you want a sum function that behaves like the Y-Combinator... okay that's a nice exercise in JavaScript – Adrian Salazar Jul 02 '15 at 16:31

3 Answers3

1

As others have mentioned, you can't quite do that. You could create a fluent interface sort of similar to that though, by extending the Number prototype:

Number.prototype.add = function(num) {
  return this.valueOf() + num;
}

Then, you could use it like this:

// Instead of add(2)(7)(11):
(0).add(2)
   .add(7)
   .add(11);

// Or:
(2).add(7).add(11);

Not sure I'd recommend actually doing that, but it's a fun exercise.

Dave Ward
  • 59,815
  • 13
  • 117
  • 134
0

You can't do that. The first set of parenthesis is there to pass the parameter to your function. You are allowed to pass more than one parameter to your function like this:

var total = add(2, 8);

Inside your add function, you be able to create a sum of every parameter using the arguments keyword:

function add() {
  var returnValue = 0;
  for (i = 0; i < arguments.length; i++) {
    returnValue += arguments[i];
  }
  return returnValue;
}

The second set of parenthesis will be applied on the value (or object) returned by your function. add(2)(8) would be the same as writing 2(8), which doesn't make sense.

The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
0

You should pass an array to your function as parameter and make a loop on it:

function add(num) {
    var sum = 0;
    for (var i = 0; i < num.length; i++) {
        sum += num[i];
    }
    return sum;
}
alert(add([10,20,30]));//will return 60
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
  • Thanks, guys. I got the answer on http://benalman.com/news/2012/09/partial-application-in-javascript/#currying-practical-uses-in-javascript – Oladipo Jul 21 '15 at 17:29