Reputation: 77
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
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
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