I've attempted a recursive string reversal below:
function reverse(str){
var results =[];
var j =0;
if(str.length === 0){
console.log('this is zero, yo');
return results.join('');
}
results[j] = str[str.length -1];
console.log('results: ' + results);
j++;
var next = str.substring(0,str.length -1);
console.log(next);
return reverse(next);
}
try{
console.log('***');
console.log(reverse('testing'));
}
catch(e){
console.log('blew the stack');
}
unfortunately, results is being set to an empty string the last time the function runs. Should I create an inner function that returns results
, so it's not set to an empty string? Is this code close?
edit: this is for curiosity's sake, i'm trying not to use the functions that make it really easy (reverse())
The problem in your code is that, you are omitting the last character every time and returning the empty string in the last recursive call.
Instead, get the last character of the string and append the reversed value of the rest of the string.
You can implement it like this
function reverse(str) {
if (str.length === 0) {
return "";
}
return str[str.length - 1] + reverse(str.substring(0, str.length - 1));
}
Here, reverse("abc")
would be evaluated like this
"c" + reverse("ab")
"c" + ("b" + reverse("a"))
"c" + ("b" + ("a" + reverse(""))) // Hits the `base condition` of recursion
"c" + ("b" + ("a" + "")) // Unwinding begins here
"c" + ("ba")
"cba"
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