File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * Counts how many times a single character appears in a string.
3+ *
4+ * @param {string } stringOfCharacters - The string to search through.
5+ * @param {string } findCharacter - The single character to count.
6+ * @returns {number } The number of times findCharacter appears in stringOfCharacters.
7+ *
8+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
9+ */
10+
111function countChar ( stringOfCharacters , findCharacter ) {
2- return 5
12+ let count = 0 ;
13+ for ( const char of stringOfCharacters ) {
14+ if ( char === findCharacter ) {
15+ count ++ ; // this means count = count + 1. This term is called
16+ // "incrementing" the count variable.
17+ }
18+ }
19+ return count ;
320}
421
522module . exports = countChar ;
Original file line number Diff line number Diff line change @@ -22,3 +22,20 @@ test("should count multiple occurrences of a character", () => {
2222// And a character `char` that does not exist within `str`.
2323// When the function is called with these inputs,
2424// Then it should return 0, indicating that no occurrences of `char` were found.
25+
26+ // test for Scenario "No Occurrences" — char isn't in the string, expect 0
27+ test ( "should return 0 when the character is not found" , ( ) => {
28+ const str = "fiendish" ;
29+ const char = "a" ;
30+ const count = countChar ( str , char ) ;
31+ expect ( count ) . toEqual ( 0 ) ;
32+ } ) ;
33+
34+ // extra edge case — counts 's' in "Mississippi" (should be 4)
35+ // Good real-world style input to make sure the loop works across a longer string.
36+ test ( "should count occurrences correctly in a mixed string" , ( ) => {
37+ const str = "Apple" ;
38+ const char = "p" ;
39+ const count = countChar ( str , char ) ;
40+ expect ( count ) . toEqual ( 2 ) ;
41+ } ) ;
You can’t perform that action at this time.
0 commit comments