Skip to content

Commit ded405e

Browse files
author
Payman IB
committed
Implement repeat function with error handling for negative counts and add corresponding tests
1 parent 9e894a7 commit ded405e

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

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

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
1-
function repeat() {
2-
return "hellohellohello";
1+
function repeat(str , count) {
2+
if (count < 0) {
3+
return "Count must be a non-negative integer";
4+
}
5+
if (count === 0) {
6+
return "";
7+
}
8+
for (let i = 0; i < count; i++) {
9+
return str.repeat(count);
10+
}
311
}
12+
console.log(repeat("hello", -2));
13+
14+
415

516
module.exports = repeat;

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

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
// Implement a function repeat
22
const repeat = require("./repeat");
3-
// Given a target string str and a positive integer count,
4-
// When the repeat function is called with these inputs,
5-
// Then it should:
6-
73
// case: repeat String:
84
// Given a target string str and a positive integer count,
95
// When the repeat function is called with these inputs,
@@ -20,13 +16,29 @@ test("should repeat the string count times", () => {
2016
// Given a target string str and a count equal to 1,
2117
// When the repeat function is called with these inputs,
2218
// Then it should return the original str without repetition, ensuring that a count of 1 results in no repetition.
23-
19+
test("should return the original string when count is 1", () => {
20+
const str = "world";
21+
const count = 1;
22+
const repeatedStr = repeat(str, count);
23+
expect(repeatedStr).toEqual("world");
24+
});
2425
// case: Handle Count of 0:
2526
// Given a target string str and a count equal to 0,
2627
// When the repeat function is called with these inputs,
2728
// Then it should return an empty string, ensuring that a count of 0 results in an empty output.
28-
29+
test("should return an empty string when count is 0", () => {
30+
const str = "test";
31+
const count = 0;
32+
const repeatedStr = repeat(str, count);
33+
expect(repeatedStr).toEqual("");
34+
});
2935
// case: Negative Count:
3036
// Given a target string str and a negative integer count,
3137
// When the repeat function is called with these inputs,
3238
// Then it should throw an error or return an appropriate error message, as negative counts are not valid.
39+
test("should return a message for negative count", () => {
40+
const str = "error";
41+
const count = -2;
42+
const repeatedStr = repeat(str, count);
43+
expect(repeatedStr).toEqual("Count must be a non-negative integer");
44+
});

0 commit comments

Comments
 (0)