Skip to content

Commit b498ab0

Browse files
committed
test: add cases for count of 0 and negative count in repeatStr function
1 parent 2e25623 commit b498ab0

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ const repeatStr = require("./repeat-str");
44
// When the repeatStr function is called with these inputs,
55
// Then it should:
66

7+
// Clean Code example, Gherkin style (Given/When/Then)
8+
79
// Case: handle multiple repetitions:
810
// Given a target string `str` and a positive integer `count` greater than 1,
911
// When the repeatStr function is called with these inputs,
@@ -20,13 +22,38 @@ test("should repeat the string count times", () => {
2022
// Given a target string `str` and a `count` equal to 1,
2123
// When the repeatStr function is called with these inputs,
2224
// Then it should return the original `str` without repetition.
25+
test("Should return the original string if count is 1", () => {
26+
expect(repeatStr("singleStf", 1)).toBe("singleStf");
27+
});
28+
2329

2430
// Case: Handle count of 0:
2531
// Given a target string `str` and a `count` equal to 0,
2632
// When the repeatStr function is called with these inputs,
2733
// Then it should return an empty string.
34+
test("Should return an empty string if the count is 0", () => {
35+
expect(repeatStr("hello", 0)).toBe("");
36+
});
2837

2938
// Case: Handle negative count:
3039
// Given a target string `str` and a negative integer `count`,
3140
// When the repeatStr function is called with these inputs,
3241
// Then it should throw an error, as negative counts are not valid.
42+
test("Should throw an error if the count is negative", () => {
43+
expect(() => repeatStr("hi", -3)).toThrow();
44+
});
45+
46+
function repeatStr(str, count) {
47+
if (count < 0) {
48+
throw new Error("count cannot be negative");
49+
}
50+
if (count === 1) return str;
51+
52+
let result = "";
53+
for (let i = 0; i < count; i++) {
54+
result = result + str;
55+
}
56+
return result;
57+
}
58+
59+
module.exports = repeatStr;

0 commit comments

Comments
 (0)