The function determines the number of certain characters in a string.
function countSymbolRec(str, symbol, count) {
if (str[str.length - 1] === symbol) count ++;
if (str.length === 1) return console.log(count);
countSymbolRec(str.slice(0, -1), symbol, count);
}
countSymbolRec("lkjkBBSlkl", "B", 0); // 2
3
Answers
Use
indexOf
!This has the advantage that the recursion stack will have the same number of layers as the number of occurrences of
symbol
onstr
.On the other hand, your implementation’s recursion stack will contain the same number of layers as the length of
str
.Compare these:
str
of length L will not contain any instances ofsymbol
. Your implementation will have a recursion stack size of L, while this solution will have a size of 1str
of length L will contain L/2 instances ofsymbol
. Your implementation will have a recursion stack size of L, while this solution will have a size of L/2str
of length L will be composed of onlysymbol
characters. Both your implementation and this solution will have a recursion stack size of LSo in most cases, the stack size of this solution is smaller than yours. This is a great improvement, specially for large strings.
In addition to @enzo’s answer: you can use an internal recursive function
You can avoid
String::slice()
since that’s slow (creates a new string) and pass the index to look the symbol at as an optional parameter: