How can I implement this logic add (1) (2) (1) .. upto (n)?

I know that this question has already been answered with disabilities, but I want it with n number of times 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 that this only works when I add extra empty brackets () it doesn't work if I do this add(1)(2)(3)

reference question

+4
source share
3 answers

Try the following:

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

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

    return fn;
}
+4
source

The following code works the same as you asked:

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

Note that some operations will determine the result specified as a function, but any functions that require a string or integer will see the correct value.

0

, .

. .

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

add(new Array(1,2,3));
-2

All Articles