alrighty then
alrighty then

Reputation: 77

recursive range function not working

I'm trying to teach myself recursion by doing a range function recursively. I can't understand why the code below isn't working?

Iterative version:

function rangeList(num, num2) {
  var arr = [];
  for (var i = num; i < num2; i++) {
    arr.push(i);
  }
  return arr;
}

Recursive version:

function rangeRecursive(num, num2) {
  return (num2 > num) ? rangeRecursive(num2 - 1).concat(num2) : []
}

console.log(rangeList(1, 7)); // returns [1, 2, 3, 4, 5, 6]
console.log(rangeRecursive(1, 7)); // returns [7]

Upvotes: 6

Views: 178

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172528

You are missing the parameter in your recursive function. It should be like this:

function rangeRecursive(num, num2) 
{
  return num2 > num ? rangeRecursive(num, num2 - 1).concat(num2) : [num]
}

Upvotes: 1

JSelser
JSelser

Reputation: 3630

It doesn't work because you are missing a parameter in your recursive call

It should be like this

function rangeRecursive(num, num2) {
  return (num2 >= num) ? rangeRecursive(num /*this was missing*/, num2 - 1).concat(num2) : []
}

Also notice the changed condition on the ternary, otherwise it stops at 1 and doesn't concat it. Either you can use >= or the following

return num2 > num ? rangeRecursive(num, num2 - 1).concat(num2) : [num]

Upvotes: 5

Related Questions