I wrote a function yesterday to count the number of \"a\" characters in a string. My teacher told me to refactor the code into a recursive function and I don\'t
Try this:
function numberOfA(n) {
return n == "" ? 0 : (n.charAt(0) == "a" ? 1 : 0) + numberOfA(n.substring(1))
}
Here's how it works:
n is the empty string, return 0 and finish the recursion. This is the base case of the recursion."a" add one, if not add zero and either way advance the recursion by removing the first character from the string. This is the recursive step of the recursion.As you can see, every recursive solution must have at least a base case and a recursive step.