1

I'm pretty new to JavaScript programming but I had experience in so many other programming languages. The idea of recursive functions in JavaScript is a fresh subject for me and I didn't see anything similar in other languages that I worked with. So for the sake of practicing, I decided to write some of the programs that I already have written with "for loops".

One of these programs is a function that takes a string as its argument and reports how many B letters are in it. Using objective-oriented programming, I first declared a function that can find the number of any other characters within a string. The program is as follows,

function countChar(string, char) {
  let counted = 0;
  for (let index = 0; index < string.length; index++) {
    if (string[index].toUpperCase() == char.toUpperCase()) {
      counted += 1;
    }
  }
  return counted;
}

function countBs(text) {
  return countChar(text, 'B');
}

console.log(countBs('Baby'));
// output = 2

It works very well but now that I'm using recursive functions, I get the "Maximum call stack size" error. My program with recursive functions looks like this one,

function countChar(string, char) {
  function cursor(i, counted) {
    if (i == string.length) {
      return counted;
    } else if (string[i].toUpperCase() == char.toUpperCase()) {
      return cursor(i++, counted++);
    } else {
      return cursor(i++, counted);
    }
  }
  return cursor(0,0);
}

function countBs(text) {
  return countChar(text, 'B');
}

console.log(countBs('Baby'));
// output must be 2 but I get 'Maximum call stack size' error instead :(

Can anybody offers a modification to this program in order to get the solution? Is it basically possible to write this program by using the recursive functions?

1
  • 1
    Consider renaming string and char to some not-so-system names. Commented Nov 14, 2018 at 16:08

1 Answer 1

4

because

 return cursor(i++, counted++);

has to be

 return cursor(i + 1, counted + 1);

(as you want to increase the value passed recursively, not the local variable i)


How i would do that:

 const countBs = (str, i = 0) => 
    i >= str.length
      ? 0
      : countBs(str, i + 1) + (str[i].toUpperCase() === "B");

Or if you plan to use it for very very long strings, allow for TCO:

 function countBs(str, i = 0, count = 0) {
   if(i >= str.length) return count;
   return countBs(str, i + 1, count + (str[i].toUpperCase === "B"));
}
Sign up to request clarification or add additional context in comments.

2 Comments

@JonasWilms So "++" operator just works locally? Is that why it works fine with index++ in for loop?
@saeed it evaluates to index, and then afterwards increases it.

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.