0

As the title suggests, I was trying to recursively solve a JavaScript problem. An exercise for my internet programming class was to invert any string that was entered in the function, and I saw this as a good opportunity to solve this with recursion. My code:

function reverseStr(str){
  str = Array.from(str);
  let fliparray = new Array(str.length).fill(0);
  let char = str.slice(-1);
  fliparray.push(char);
  str.pop();
  str.join("");
  return reverseStr(str);
}
writeln(reverseStr("hello"))
4
  • 3
    Your recursion does not have a base case. Commented Feb 7, 2017 at 4:05
  • what is the ending condition? Commented Feb 7, 2017 at 4:05
  • Can you comment on what each line is supposed to do, and how your recursive algorithm works? Maybe demonstrate the steps that should be taken on an example string. Commented Feb 7, 2017 at 4:07
  • 2
    FYI, you have fliparray, which isn't actually getting used, you have str.join(""), which doesn't reference its result, and you're reusing variables in a confusing way. Create a new variable when you do Array.from(str) so that it doesn't look like you're calling invalid methods on a string. Commented Feb 7, 2017 at 4:09

1 Answer 1

1

The biggest problem is that your function doesn't have an end (base) case. It needs to have some way to recognize when it's supposed to stop or it will recurse forever.

The second problem is that you don't really seem to be thinking recursively. You're making some modification to the string, but then you just call reverseStr() all over again on the modified string, which is just going to start the process all over again.

The following doesn't really resemble your attempt (I don't know how to salvage your attempt), but it is a simple way to implement the reverse string algorithm recursively.

function reverseStr(str) {
  // string is 0 or 1 characters. nothing to reverse
  if (str.length <= 1) {
    return str;
  }

  // return the first character appended to the end of the reverse of 
  // the portion after the first character
  return reverseStr(str.substring(1)) + str.charAt(0);
}

console.log(reverseStr("Hello Everybody!"));

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I've salvaged the code to what I needed, but your response helped a lot, even though the real error was an id10t

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.