Momogi
Momogi

Reputation: 23

How to ilterate with recursive function (javascript)

function numberSum(num) {

  var str = num.toString();
  var arrNum = str.split('').map(Number);//arrNum = [1, 2, 3];

  //For-looping
  var result = 0;
  for (var i = 0; i < arrNum.length; i++) {
    result = result + arrNum[i];
  }
  return result;
}


console.log(numberSum(22222)); // 2 + 2 + 2 + 2 + 2 = 10

I did this with For-looping and then iterate it. The question is, how do i did the same but with Recursive Function?

Upvotes: 1

Views: 77

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386736

You could use only the first element for addition and call the function with the rest of the array again.

In this case, a check is made for the length, this returns either 0 if the array has no items or the item count, then a shift is made which returns the first item of the array. Additionaly the function is called again with the reduced array.

function iter(array) {
    return array.length && array.shift() + iter(array);
    //     ^^^^^^^^^^^^                                 exit condition,
    //                                                  if zero, return zero, 
    //                                                  otherwise return the
    //                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^  iteration part
    //                                                  return the first value and
    //                                                  call recursion again
}

function numberSum(v) {
    function iter(array) {
        return array.length && array.shift() + iter(array);
    }

    return iter(v.toString().split('').map(Number));
}

console.log(numberSum(22222)); // 2 + 2 + 2 + 2 + 2 = 10

Upvotes: 2

Brian Peacock
Brian Peacock

Reputation: 1849

For the input you have (22222) your function is a practical solution. If you want a function that takes a number and adds itself together a certain number of times you can simply do this...

function sums(a, b) {
    return a * b;
}
sums(2, 5);
//=> 10

But if you really require an example of a recursive function to do this the following will achieve the same result...

var num = 2;
var iterate = 5;

function sums(n, count, total) {
    if (count === 0) {
        return total;
    } else {
        return sums(n, --count, total+n);
    }
}
console.log(sums(num, iterate, 0));
//=> 10

Hope that helped. :)

(See this blog post on JavaScript recursion by integralist).

Upvotes: 0

Related Questions