Bean counting

by Shridhar Baddur

JavaScript

//Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters are in the string.

/*function countBs(str) {
  var count = 0;
  for (var n = 0; n < str.length; n++) {
    if (str[n] === "B")
      count++;
  }
  return count;
}
console.log(countBs("BBC News is the Best in the world"));
*/
//Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function.

function countChar(str, char) {
  var count = 0;
  for (var n = 0; n < str.length; n++) {
    if (str[n] === char)
      count++;
  }
  return count;
}

function countBs(str) {
  return countChar(str, "B");
}
console.log(countBs("BBC News is the best in the world"));
console.log(countChar("kakkerlak", "k"));