Skip to content

Commit c6721c6

Browse files
Implement repeatStr function with error handling and add tests for various cases
1 parent a4fe335 commit c6721c6

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed
Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
function repeatStr() {
2-
return "hellohellohello";
1+
function repeatStr(str, count) {
2+
if (count < 0) {
3+
throw new Error("Count must be non-negative");
4+
}
5+
if (count === 0) {
6+
return "";
7+
}
8+
return str.repeat(count);
39
}
4-
510
module.exports = repeatStr;

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,28 @@ test("should repeat the string count times", () => {
1515
const repeatedStr = repeatStr(str, count);
1616
expect(repeatedStr).toEqual("hellohellohello");
1717
});
18+
// Case: handle count of 1:
19+
test("should return the string when count is 1", () => {
20+
const str = "hello";
21+
const count = 1;
22+
const repeatedStr = repeatStr(str, count);
23+
expect(repeatedStr).toEqual("hello");
24+
});
25+
26+
// Case: Handle count of 0:
27+
test("should return an empty string when count is 0", () => {
28+
const str = "hello";
29+
const count = 0;
30+
const repeatedStr = repeatStr(str, count);
31+
expect(repeatedStr).toEqual("");
32+
});
1833

34+
// Case: Handle negative count:
35+
test("should throw an error when count is negative", () => {
36+
const str = "hello";
37+
const count = -1;
38+
expect(() => repeatStr(str, count)).toThrow();
39+
});
1940
// Case: handle count of 1:
2041
// Given a target string `str` and a `count` equal to 1,
2142
// When the repeatStr function is called with these inputs,

0 commit comments

Comments
 (0)