5

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

Rico
  • 53
  • 1
  • 4
  • I don't get what you want to do with that `results` array. Try to write a code without any arrays, only using sting slicing and concatenation. – Bergi Dec 11 '14 at 04:45
  • i originally had done this using a while loop. but i'm learning that i can't declare variables in recursive functions like normal ones. – Rico Dec 11 '14 at 04:51
  • Well, you *could* do such with an inner function - declaring `results` outside of the actual recursive function, which would take the part of the while loop (and recurse over `j`); but I think that's not the point of your exercise. – Bergi Dec 11 '14 at 04:53

1 Answers1

6

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"
thefourtheye
  • 233,700
  • 52
  • 457
  • 497