I'm a pretty experienced frontend engineer with a weak CS background. I'm trying to get my head around the concept of recursion. Most of the examples and purported explanations I can find just aren't explaining it in a way I find easy to understand.
I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.
Could someone provide a sample function?
function reverseString(str) { if (str === "") // This is the terminal case that will end the recursion return ""; else return reverseString(str. substr(1)) + str.
Example 2: Reverse a String Using built-in Methods split("") gives ["h", "e", "l", "l", "o"] . The string elements are reversed using the reverse() method. arrayStrings. reverse() gives ["o", "l", "l", "e", "h"] .
Something like:
function reverse (str) {
if (str === "") {
return "";
} else {
return reverse(str.substr(1)) + str.charAt(0);
}
}
So the function is recursive as it calls itself to do the work.
A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):
function reverse(str) {
function r(s, acc) {
return (s.length == 0) ? acc : r(s.substr(1), s.charAt(0) + acc);
};
return r(str, '');
};
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