0

I am trying to create a function "sum" that adds multiple numbers using an inner function. e.g. sum(1)(2) will print 3 sum(1)(2)(3) will print 6 sum(1)(2)(3)(4) will print 10 and so on

I wrote the following code which works for sum(1)(2).

function sum(num){
    function add (b){
        console.log(num+=b);
    }
    return add;
}

How can I extend this to work with multiple calls to inner function?

Deepak
  • 1
  • 2
  • Currying and dynamic arity are not compatible. – elclanrs Jul 10 '14 at 22:15
  • There's some problems here. You need to pass b in somewhere. Ideally this function will take 2 arguments, and add them together. – Kolby Jul 10 '14 at 22:15
  • *sum* needs to return itself with the current value perhaps as a property or held in a closure. The trick will be clearing it the next time it's called. – RobG Jul 10 '14 at 22:19
  • Add `return add;` as the last line of the inner `add` function. I tried posting this as an answer but it was closed. Note that this *prints* the answer, but does not *return* it. – Matt Jul 10 '14 at 22:34
  • Thanks Bergi for pointing me to the correct solution. – Deepak Jul 10 '14 at 22:44

2 Answers2

0

This is how I would handle it. Just a single function that accepts 2 numbers. Adds those 2 numbers and returns the sum.

function sum(num1, num2){
    return num1+num2;
}

console.log(sum(11, 10));

http://jsfiddle.net/PpsjJ/

Update: I think this is what you want. A function that accepts an array of numbers, and then adds them all together.

function sumAll(numbers){
    var result = 0;
    numbers.forEach(function(value, key){
        result += value;
    });
    return result;
}

console.log(sumAll([1,2,3]));

http://jsfiddle.net/PpsjJ/1/

Kolby
  • 2,775
  • 3
  • 25
  • 44
0

I think what you are looking is summing variable number of arguments. What about this:

function sum() {
  var total = 0;
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }

  alert(total);
}

sum(1,2,3,4,5,6);

Prints: 21

You can call sum with any number of arguments.

rageit
  • 3,513
  • 1
  • 26
  • 38