Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript recursion reverse string [duplicate]

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())

like image 248
Rico Avatar asked Dec 11 '14 04:12

Rico


1 Answers

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"
like image 199
thefourtheye Avatar answered Oct 12 '22 10:10

thefourtheye