Skip to content

Commit f77b982

Browse files
committed
Implement countChar and add Jest tests using TDD
1 parent cce7c24 commit f77b982

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

Sprint-3/2-practice-tdd/count.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,22 @@
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+
111
function 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

522
module.exports = countChar;

Sprint-3/2-practice-tdd/count.test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
});

0 commit comments

Comments
 (0)