You can always start with the basic structure of the recursive function. All recursive functions will have this structure:
func recur( . . . ) {
if (is_it_an_endcase?) {
//perform the end case
} else {
//perform the recursive case
// call recur() with an argument different (smaller) than the parameter received here
The key point is that you will always have a call to itself inside the function body. Your code does not have a recursive call in the function body.
Suppose you want a recursive function to print a countdown.
func countdown(n) {
for (let i = n; i >=0; i--) {
console.log(i);
}
}
How would you do this recursively? Let’s start thinking with the basic structure. What would be the end case in this problem? When the parameter n is zero, we’re done. We’ll do the final print. We have something like
func rec_countdown(n) {
if (n == 0) {
console.log(0);
} else {
//recursive case
}
}
To think the recursive case, you can imagine yourself as a recursive function and there are multiple clones of you. You take one finite action and delegate to your clone to finish up the remaining task. You can think like this
func rec_countdown(n) {
if (n == 0) {
console.log(0);
} else {
console.log(n);
//recursive case: since you printed out n, you ask your clone to take care of
//count down from n-1
rec_countdown(n-1);
}
}
Now, the function rec_countdown() does not return any value (i.e., there’s no explicit ‘return’ statement). It gets slightly harder when you have to return a value in a recursive function, but the basic structure remains the same.
Suppose you want to build a list containing n numbers of a string “hello”. You can think recursively like this: You get N as a parameter. You ask your clone to create a list of N-1 ‘hello’. You then add one more ‘hello’ and pass the result back to your caller. If the passed parameter is 0 then you return an an empty list.
func rec_create(n) {
if (n == 0) { //or n <= 0 to handle negatives
return [];
} else {
let arr = rec_create(n-1); //your clone returns a list of n-1 'hello's
arr.push("hello"); //you add one more 'hello' to the list; now there's n 'hello's
return arr; //then you return the result to your caller
}
}
For the rangeOfNumbers function, you can build the list either backward or forward. If you have low and high as parameters, your clone can build a list of [low+1, …, high] or [low, … , high-1].
As mentioned, recursion is hard. I hope this helps.