0

I tried to solve the following problem without using the for loop:

"Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
console.log(countBs("BBC")); // → 2

Thank you for your help.

Here is the code I wrote so far which doesn't work:

function countBs(word) {
  let count = 0
  if (word.length == 0) {
    return count;
  } else {
    if (word[word.length - 1] == 'B') {
      count++
    }
    return countBs(word.slice(0, word.length - 1))
  }
}
console.log(countBs("BBC"))
Lucas Erlacher
  • 23
  • 1
  • 2
  • 7
  • Are you supposed to use recursion for this, or why this approach? – CBroe Jul 07 '20 at 11:39
  • 1
    Does this answer your question? [How to count string occurrence in string?](https://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) – Argee Jul 07 '20 at 11:39
  • 1
    `return count + countBs(word.slice(0, word.length - 1));` – 001 Jul 07 '20 at 11:42
  • @CBroe I was just trying to understand if recursion can be used for this without using for loop or regex. – Lucas Erlacher Jul 07 '20 at 11:48
  • @Argee no it seems not. Thank you though. – Lucas Erlacher Jul 07 '20 at 11:49
  • @JohnnyMopp thank you for your reply. I tried to implement but it still returns undefined. – Lucas Erlacher Jul 07 '20 at 11:49
  • Sure recursion _could_ be used here - but it has little advantage over a simple loop. If anything, it has disadvantages, due to the call stack size recursive calls will cause. – CBroe Jul 07 '20 at 11:50
  • @LucasErlacher Works for me: https://jsfiddle.net/ubwnvkh8/ – 001 Jul 07 '20 at 12:02
  • @JohnnyMopp you're right. I placed it in the wrong bracket. Thanks a lot for your solution. – Lucas Erlacher Jul 07 '20 at 12:08
  • `function countBs(word, count = 0) { if (word.length == 0) { return count; } else { if (word[word.length - 1] == 'B') { count++ } return countBs(word.slice(0, word.length - 1), count) } } console.log(countBs("BBC"))` would be how you can modify your code... – Argee Jul 07 '20 at 12:25
  • Because a string can be destructured into an array, we can write a fairly simply recursive version: `const countBs = ([c, ...cs]) => c == undefined ? 0 : (c === 'B' ? 1 : 0) + countBs(cs)`. We could fairly easily convert it to tail-recursive, if TCO ever becomes a JS reality. – Scott Sauyet Jul 07 '20 at 12:37
  • Thank you @ScottSauyet – Lucas Erlacher Jul 08 '20 at 16:17

1 Answers1

0

You can easily use regex for this case:

function countBs(word) {
  const matches = word.match(/B/g);

  return matches && matches.length || 0;
}

Basically it globally searches for occurrences of 'B'. If it find it, it returns the length of it, if the matches are null it will return 0.

Simpler less expressive:

function countBs(word) {
  return (word.match(/B/g) || []).length;
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149