Skip to content

Commit f097ae0

Browse files
committed
created test-case for repeat and tested the cases with a pass
1 parent c40ecef commit f097ae0

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

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

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
11
function repeat() {
2-
return "hellohellohello";
2+
if (arguments.length !== 2) {
3+
throw new Error("Function requires exactly two arguments: str and count.");
4+
}
5+
6+
const [str, count] = arguments;
7+
8+
if (typeof str !== "string") {
9+
throw new Error("First argument must be a string.");
10+
}
11+
12+
if (typeof count !== "number" || !Number.isInteger(count) || count < 0) {
13+
throw new Error("Second argument must be a non-negative integer.");
14+
}
15+
16+
if (count === 0) {
17+
return "";
18+
}
19+
20+
if (count === 1) {
21+
return str;
22+
}
23+
24+
let result = "";
25+
for (let i = 0; i < count; i++) {
26+
result += str;
27+
}
28+
return result;
329
}
430

531
module.exports = repeat;

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,35 @@ test("should repeat the string count times", () => {
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.
2323

24+
test("should return the original string when count is 1", () => {
25+
const str = "world";
26+
const count = 1;
27+
const repeatedStr = repeat(str, count);
28+
expect(repeatedStr).toEqual("world");
29+
});
30+
2431
// case: Handle Count of 0:
2532
// Given a target string str and a count equal to 0,
2633
// When the repeat function is called with these inputs,
2734
// Then it should return an empty string, ensuring that a count of 0 results in an empty output.
2835

36+
test("should return an empty string when count is 0", () => {
37+
const str = "test";
38+
const count = 0;
39+
const repeatedStr = repeat(str, count);
40+
expect(repeatedStr).toEqual("");
41+
});
42+
2943
// case: Negative Count:
3044
// Given a target string str and a negative integer count,
3145
// When the repeat function is called with these inputs,
3246
// Then it should throw an error or return an appropriate error message, as negative counts are not valid.
47+
48+
test("should throw an error for negative count", () => {
49+
const str = "error";
50+
const count = -2;
51+
expect(() => repeat(str, count)).toThrow(
52+
"Second argument must be a non-negative integer."
53+
);
54+
});
55+

0 commit comments

Comments
 (0)