JavaScript Reverse Recursion String

I tried recursively canceling the lines 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, the results are set to an empty line the last time the function is run. Should I create an internal function that returns results, so it is not set to an empty string? Is this code private?

edit: this is for the sake of curiosity, I try not to use functions that make it very easy (reverse ())

+4
source share
1 answer

The problem in your code is that you omit the last character each time and return an empty string to the last recursive call.

Instead, get the last character of the string and add the inverse of the rest of the string.

function reverse(str) {
    if (str.length === 0) {
        return "";
    }

    return str[str.length - 1] + reverse(str.substring(0, str.length - 1));
}

reverse("abc")

"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"
+3

All Articles