Skip to content

Commit 6da58b9

Browse files
committed
Implement repeatStr function with input validation and enhance test coverage
1 parent 0280acb commit 6da58b9

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed
Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,14 @@
1-
function repeatStr() {
2-
return "hellohellohello";
1+
function repeatStr(str, count) {
2+
if (typeof count !== "number" || count < 0) {
3+
throw new Error("Count must be a non-negative integer");
4+
}
5+
6+
let result = "";
7+
for (let i = 0; i < count; i++) {
8+
result += str;
9+
}
10+
11+
return result;
312
}
413

514
module.exports = repeatStr;

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

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,40 @@ const repeatStr = require("./repeat-str");
1010
// Then it should return a string that contains the original `str` repeated `count` times.
1111

1212
test("should repeat the string count times", () => {
13-
const str = "hello";
14-
const count = 3;
15-
const repeatedStr = repeatStr(str, count);
16-
expect(repeatedStr).toEqual("hellohellohello");
13+
expect(repeatStr("hello", 3)).toEqual("hellohellohello");
1714
});
1815

1916
// Case: handle count of 1:
2017
// Given a target string `str` and a `count` equal to 1,
2118
// When the repeatStr function is called with these inputs,
2219
// Then it should return the original `str` without repetition.
2320

21+
test("should return the original string when count is 1", () => {
22+
expect(repeatStr("world", 1)).toEqual("world");
23+
});
24+
2425
// Case: Handle count of 0:
2526
// Given a target string `str` and a `count` equal to 0,
2627
// When the repeatStr function is called with these inputs,
2728
// Then it should return an empty string.
2829

30+
test("should return an empty string when count is 0", () => {
31+
expect(repeatStr("test", 0)).toEqual("");
32+
});
33+
2934
// Case: Handle negative count:
3035
// Given a target string `str` and a negative integer `count`,
3136
// When the repeatStr function is called with these inputs,
3237
// Then it should throw an error, as negative counts are not valid.
38+
39+
test("should throw an error when count is negative", () => {
40+
expect(() => {
41+
repeatStr("error", -2);
42+
}).toThrow("Count must be a non-negative integer");
43+
});
44+
45+
test("should throw an error when count is not a number", () => {
46+
expect(() => {
47+
repeatStr("error", "-2");
48+
}).toThrow("Count must be a non-negative integer");
49+
});

0 commit comments

Comments
 (0)