Skip to content

Commit 5233e20

Browse files
committed
refactor countChar and repeat functions to improve argument validation and error handling
1 parent dad2134 commit 5233e20

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,28 @@
11
function countChar(stringOfCharacters, findCharacter) {
2+
23
if (stringOfCharacters === undefined || findCharacter === undefined) {
34
throw new Error(
45
"Function requires exactly two arguments: a string and a character to find."
56
);
67
}
8+
79
if (typeof stringOfCharacters !== 'string'){
810
throw new Error("First argument must be a string.");
911
}
12+
1013
if (typeof findCharacter !== "string") {
1114
throw new Error("Second argument must be a string.");
1215
}
16+
1317
if (findCharacter.length !== 1) {
1418
throw new Error("Character to find must be a single character.");
1519
}
20+
1621
if (!stringOfCharacters.length) {
1722
return 0;
18-
}
19-
return Array.from(stringOfCharacters).filter(char => char === findCharacter).length;
23+
}
24+
25+
return [...stringOfCharacters].filter(char => char === findCharacter).length;
2026
}
2127

2228
module.exports = countChar;

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
function repeat(str, count) {
2+
23
if ( arguments.length !== 2) {
34
throw new Error(`Function requires exactly two arguments: a string and a count. Received ${arguments.length} arguments`);
45

56
}
7+
68
if (typeof str !== "string") {
79
throw new Error("First argument must be a string. Received type " + typeof str);
810
}
11+
912
if (!Number.isInteger(count) || count < 0) {
1013
throw new Error("Second argument must be a non-negative integer. Received " + count );
1114
}
15+
1216
return str.repeat(count);
1317
}
1418

0 commit comments

Comments
 (0)