Skip to content

Commit 0f8bc3b

Browse files
committed
implement function to count character occurrences, including case-sensitive and non-alphabet characters
1 parent 2f7741e commit 0f8bc3b

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
function countChar(stringOfCharacters, findCharacter) {
2-
return 5
2+
if (typeof stringOfCharacters !== "string") {
3+
throw new Error("First argument must be a string");
4+
}
5+
if (typeof findCharacter !== "string" || findCharacter.length !== 1) {
6+
throw new Error("Second argument must be a single character");
7+
}
8+
9+
let count = 0;
10+
for (const char of stringOfCharacters) {
11+
if (char === findCharacter) {
12+
count++;
13+
}
14+
}
15+
return count;
316
}
417

5-
module.exports = countChar;
18+
module.exports = countChar;

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,27 @@ test("should return 0 when the character does not occur in the string", () => {
2828
const count = countChar(str, char);
2929
expect(count).toEqual(0);
3030
});
31+
32+
// Case: Case sensitivity
33+
test("should count characters in a case-sensitive way", () => {
34+
const str = "Hello World";
35+
const char = "h"; // lowercase 'h' does not match 'H'
36+
const count = countChar(str, char);
37+
expect(count).toEqual(0);
38+
});
39+
40+
// Case: Non-alphabet characters
41+
test("should count non-alphabet characters", () => {
42+
const str = "123!@#123!";
43+
const char = "1";
44+
const count = countChar(str, char);
45+
expect(count).toEqual(2);
46+
});
47+
48+
// Case: Spaces
49+
test("should count spaces correctly", () => {
50+
const str = "a b c d e f g";
51+
const char = " ";
52+
const count = countChar(str, char);
53+
expect(count).toEqual(6);
54+
});

0 commit comments

Comments
 (0)