4

I know this question is already answered with limited capability but I want it with n number of time with n arguments?

function add(x) {
    return function(y) {
        if (typeof y !== 'undefined') {
            x = x + y;
            return arguments.callee;
        } else {
            return x;
        }
    };
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6

problem is this works only when I add extra empty brackets () it doesn't work if do this add(1)(2)(3)

reference question

Community
  • 1
  • 1
Shahzad
  • 550
  • 1
  • 6
  • 24
  • You should make your question clear – Andre Pena Dec 24 '13 at 07:10
  • @AndréPena the question is clear, perhaps you are simply not experienced enough in this style of javascript programming to understand it. – Entoarox Dec 24 '13 at 07:11
  • I think it's clear. He wants to curry a function unlimited times without having to execute the last function, getting the value right away. It is not possible, those things can't coexist. But, you can abuse `toString` or `valueOf`. – elclanrs Dec 24 '13 at 07:13
  • @elclanrs javascript can perform the `toString` method automatically in cases where an object is treated like a string, so it is possible, it just comes with a few caveats in the fact that it is an object that can be read as a string. (such as typeof equalling 'function', and other minor strangeness issues) – Entoarox Dec 24 '13 at 07:16
  • That's what I meant by "abuse". – elclanrs Dec 24 '13 at 07:17

3 Answers3

4

Try this:

function add(x) {
    var fn = function(y) {
        x = x + y;
        return arguments.callee;
    };

    fn.toString = function(){  return x; };

    return fn;
}
CD..
  • 72,281
  • 25
  • 154
  • 163
0

The following code works exactly like you asked:

function add(a)
{
    var c=a,b=function(d){c+=d;return arguments.callee;};
    b.toString=function(){return c;}return b;
}

Do note that some operations will detect the result given as a function, but any functions that require a string or integer will see the proper value.

Entoarox
  • 703
  • 4
  • 8
-2

Try sending your numbers as an array and changing your function code to reflect these changes.

Note: Code untested.

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

add(new Array(1,2,3));
Matt
  • 36
  • 1
  • The whole point here was to enable use of a special syntax, an array is not even needed if you just want to add arbitrary numbers in a function. – Entoarox Dec 24 '13 at 07:10