Skip to content

Commit bedc468

Browse files
committed
Refactor repeat function to handle input validation and add comprehensive test cases
1 parent 1570edd commit bedc468

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
function repeat() {
2-
return "hellohellohello";
1+
function repeat(str, count) {
2+
if (typeof str !== "string") throw new Error("Input must be a string");
3+
if (typeof count !== "number" || count < 0)
4+
throw new Error("Count must be a non-negative number");
5+
return str.repeat(count);
36
}
47

58
module.exports = repeat;

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,41 @@ test("should repeat the string count times", () => {
2020
// Given a target string str and a count equal to 1,
2121
// When the repeat function is called with these inputs,
2222
// Then it should return the original str without repetition, ensuring that a count of 1 results in no repetition.
23+
test("should return the original string when count is 1", () => {
24+
const str = "world";
25+
const count = 1;
26+
const repeatedStr = repeat(str, count);
27+
expect(repeatedStr).toEqual("world");
28+
});
2329

2430
// case: Handle Count of 0:
2531
// Given a target string str and a count equal to 0,
2632
// When the repeat function is called with these inputs,
2733
// Then it should return an empty string, ensuring that a count of 0 results in an empty output.
34+
test("should return an empty string when count is 0", () => {
35+
const str = "test";
36+
const count = 0;
37+
const repeatedStr = repeat(str, count);
38+
expect(repeatedStr).toEqual("");
39+
});
2840

2941
// case: Negative Count:
3042
// Given a target string str and a negative integer count,
3143
// When the repeat function is called with these inputs,
3244
// Then it should throw an error or return an appropriate error message, as negative counts are not valid.
45+
test("should throw an error for a negative count", () => {
46+
const str = "error";
47+
const count = -2;
48+
expect(() => repeat(str, count)).toThrow(
49+
"Count must be a non-negative number"
50+
);
51+
});
52+
// case: Non-String Input:
53+
// Given a non-string input for str (e.g., a number, object, or array) and a positive integer count,
54+
// When the repeat function is called with these inputs,
55+
// Then it should throw an error or return an appropriate error message, as the function is expected to handle only string inputs.
56+
test("should throw an error for non-string input", () => {
57+
const str = 12345; // Non-string input
58+
const count = 2;
59+
expect(() => repeat(str, count)).toThrow("Input must be a string");
60+
});

0 commit comments

Comments
 (0)