Last active
August 12, 2020 20:03
-
-
Save kdubbels/a04ad5990d85e54a3b4780f9707ec26f to your computer and use it in GitHub Desktop.
Solution to the "Bean Counting" exercise in Chapter 3 of "Eloquent JavaScript" by Marijn Haverbeke
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from https://eloquentjavascript.net/03_functions.html#i_3rsiDgC2do | |
/* | |
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. | |
*/ | |
const countChar = (string, character) => { | |
let count = 0; | |
string.split('').forEach((x) => { | |
x === character ? count++ : null | |
}); | |
return count; | |
}; | |
const countCharUsingReduce = (string, character) => { | |
return string.split('').reduce((accumulator, currentValue) => { | |
currentValue === character ? accumulator++ : 0; | |
return accumulator; | |
}, 0); | |
}; | |
const countBs = (string) => countChar(string, 'B'); | |
console.log(countBs("BBC")); | |
// → 2 | |
console.log(countChar("kakkerlak", "k")); | |
// → 4 | |
console.log(countCharUsingReduce("kakkerlak", "k")); | |
// → 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment