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?
stringandcharto some not-so-system names.