animesh.blog

Bean counting problem

Bean counting problem from chapter 3 of Eloquent Javascript book.

Problem

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. 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 initialCountBs(sValue) {
    var bcount = 0;
    for (var i = 0; i < sValue.length; i++) {
        if (sValue.charAt(i) === 'B')
            bcount += 1;
    }
    return bcount;
}

function countBs(sValue) {
    return countChar(sValue, 'B');
}

function countChar(sValue, char) {
    var count = 0;
    for (var i = 0; i < sValue.length; i++) {
        if (sValue.charAt(i) === char)
            count += 1;
    }
    return count;
}