Skip to content

Commit e2c7e37

Browse files
committed
Implement repeat function with parameters and error handling
- Added str and count parameters to repeat function - Used String.repeat to repeat str count times - Throws error if count is negative - Added tests for count = 1, 0, and negative values
1 parent 50eaeb4 commit e2c7e37

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed
Lines changed: 6 additions & 3 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 (count < 0) {
3+
throw new Error("Count must be non-negative");
4+
}
5+
return str.repeat(count);
36
}
47

5-
module.exports = repeat;
8+
module.exports = repeat;

Sprint-3/3-mandatory-practice/implement/repeat.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,46 @@ test("should repeat the string count times", () => {
1616
expect(repeatedStr).toEqual("hellohellohello");
1717
});
1818

19+
const repeat = require("./repeat");
20+
21+
// test("should repeat the string count times", () => {
22+
// expect(repeat("hello", 3)).toEqual("hellohellohello");
23+
// });
24+
1925
// case: handle Count of 1:
2026
// Given a target string str and a count equal to 1,
2127
// When the repeat function is called with these inputs,
2228
// Then it should return the original str without repetition, ensuring that a count of 1 results in no repetition.
2329

30+
test("should return original string when count is 1", () => {
31+
expect(repeat("hello", 1)).toEqual("hello");
32+
});
33+
34+
2435
// case: Handle Count of 0:
2536
// Given a target string str and a count equal to 0,
2637
// When the repeat function is called with these inputs,
2738
// Then it should return an empty string, ensuring that a count of 0 results in an empty output.
2839

40+
test("should return empty string when count is 0", () => {
41+
expect(repeat("hello", 0)).toEqual("");
42+
});
43+
2944
// case: Negative Count:
3045
// Given a target string str and a negative integer count,
3146
// When the repeat function is called with these inputs,
3247
// Then it should throw an error or return an appropriate error message, as negative counts are not valid.
48+
49+
test("should throw error for negative count", () => {
50+
expect(() => repeat("hello", -1)).toThrow("Count must be non-negative");
51+
});
52+
53+
54+
55+
56+
57+
58+
59+
60+
61+

0 commit comments

Comments
 (0)