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]
Every time the recursive function is called, it takes up stack space (we'll discuss this more exhaustively in the section) and space for its local variables are set aside. So actually, the recursive version takes up much more space overall than does the iterative version.
The condition that stops a recursive function from calling itself is known as the base case. In the log function above, the base case is when num is larger than 5 .
Limitations of Recursive Approach:Each function call requires push of return memory address, parameters, returned result,etc. and every function return requires that many pops. 2. Each time you call a function you use up some of your memory allocation may be in stack or heap.
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]
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]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With