-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbean-counting.js
43 lines (31 loc) · 1.27 KB
/
bean-counting.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// You can get the Nth character, or letter, from a string by writing "string"[N].
// The returned value will be a string containing only one character (for example, "b").
// The first character has position 0, which causes the last one to be found at position string.length - 1.
// In other words, a two-character string has length 2, and its characters have positions 0 and 1.
// 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.
// 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 countBs(str) {
let result = 0
for(let i = 0; i < str.length; i++) {
if (str[i] === 'B') {
result += 1
}
}
return result
}
// Another solution for countBs
// const countBs = str => countChar(str, 'B')
function countChar(str, char) {
let result = 0
for(let i = 0; i < str.length; i++) {
if (str[i] === char) {
result += 1
}
}
return result
}
console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4