First of all. What is recursion?
Recursion is the process where a function calls itself. The solution of recursion problems depend on the solution of smaller instances of the same problem.
Steps for recursion
Step 1. Have a precise spec.
Step 2. Check that the method works in the base case(s).
Step 3. Look at the recursive case(s). In your mind replace each recursive call by what it does according to the spec and verify correctness.
Step 4. No recursion problem should be infinite. Make sure that the arguments of recursive calls are in some sense smaller than the parts of the method.
I am now going to discuss how to solve the problem of inverting a String using recursion. This same problem could easily be solve using a loop. However, on this case I am going to do the same thing but with the method of recursion.
1. First we create a function called: "reverseString", which is going to have "str" as an argument.
function reverseString(str) {
}
}
2. We need to know the length of the String and assign it to a variable.
function reverseString(str) {
let sLen = str.length;
}
let sLen = str.length;
}
3. The logic of the recursive functions requires that we call the function "reverseString()" as many times as necessary, knowing that everytime we call the function the argument: "str" is going to smaller and smaller.
If every time we call the function "reverseString()" we want that the input becomes smaller then the base case would be when the String's length be less or equal to 0. Therefore:
function reverseString(str) {
let sLen = str.length;
if (sLen <= 0) {
return '';
}
}
let sLen = str.length;
if (sLen <= 0) {
return '';
}
}
When we have call the function multiple times until exhaust the Strings's length we then should return an empty String.
4. The most important part of recursive functions is calling themselves. On this case, to revert a String we should first use the "chatAt()" method to get the last character of our input String and concatenate it with the result of our invoked recursive function. Because we want the String to be deleting the character that we will be adding from the back to the beginning, the input is going to be decreasing. We use the method "substring" to achieve this. This way our final code will look something like:
function reverseString(str) {
let sLen = str.length;
if (sLen <= 0) {
return '';
} else {
console.log(str.length - 1);
return str.charAt(sLen - 1) + reverseString(str.substring(0, sLen -1));
}
}