Skip to content

Commit dad2134

Browse files
committed
refactor countChar function to validate arguments and update tests for error handling
1 parent 7fabb60 commit dad2134

File tree

2 files changed

+3
-9
lines changed

2 files changed

+3
-9
lines changed

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
function countChar(stringOfCharacters, findCharacter) {
2-
if (arguments.length !== 2) {
2+
if (stringOfCharacters === undefined || findCharacter === undefined) {
33
throw new Error(
44
"Function requires exactly two arguments: a string and a character to find."
55
);
@@ -13,7 +13,7 @@ function countChar(stringOfCharacters, findCharacter) {
1313
if (findCharacter.length !== 1) {
1414
throw new Error("Character to find must be a single character.");
1515
}
16-
if (stringOfCharacters.length === 0) {
16+
if (!stringOfCharacters.length) {
1717
return 0;
1818
}
1919
return Array.from(stringOfCharacters).filter(char => char === findCharacter).length;

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,20 +97,14 @@ test.each([
9797
{ str: [], char: "a", error: "First argument must be a string." },
9898
{ str: "hello", char: {}, error: "Second argument must be a string." },
9999
{ str: null, char: "a", error: "First argument must be a string." },
100-
{str: "hi", char: undefined, error: "Second argument must be a string." },
101100
])("should throw error for invalid inputs", ({ str, char, error }) => {
102101
expect(() => {
103102
countChar(str, char);
104103
}).toThrow(error);
105104
});
106105
//test for 2 arguments
107-
test("should throw error if more/less than 2 arguments are provided", () => {
106+
test("should throw error if less than 2 arguments are provided", () => {
108107
expect(() => {
109108
countChar("hello");
110109
}).toThrow("Function requires exactly two arguments: a string and a character to find.");
111-
expect(() => {
112-
countChar("hello", "h", "extra");
113-
}).toThrow(
114-
"Function requires exactly two arguments: a string and a character to find."
115-
);
116110
});

0 commit comments

Comments
 (0)