Skip to content

Commit 4332537

Browse files
Implement repeatStr function and add comprehensive tests for various cases
1 parent e108f82 commit 4332537

2 files changed

Lines changed: 38 additions & 5 deletions

File tree

‎practice-tdd/repeat-str.js‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
1-
export function repeatStr() {
2-
// Your implementation of this function must *not* call String.prototype.repeat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat).
3-
// The goal is to re-implement that function, not to use it.
4-
return "hellohellohello";
1+
export function repeatStr(str, count) {
2+
let result = "";
3+
4+
for (let i = 0; i < count; i++) {
5+
result = result + str;
6+
}
7+
8+
if (count < 0) {
9+
throw new Error("Count cannot be negative");
10+
}
11+
return result;
512
}

‎practice-tdd/repeat-str.test.js‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,36 @@ test("should repeat the string count times", () => {
1616
expect(repeatedStr).toEqual("hellohellohello");
1717
});
1818

19+
test("should return the original 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+
test("should return an empty string", () => {
27+
const str = "hello";
28+
const count = 0;
29+
const repeatedStr = repeatStr(str, count);
30+
expect(repeatedStr).toEqual("");
31+
});
32+
33+
test("should throw an error when count is negative", () => {
34+
const str = "hello";
35+
const count = -2;
36+
expect(() => repeatStr(str, count)).toThrow();
37+
});
38+
39+
test("should return Backstreet Boys lyrics", () => {
40+
const str = "bye";
41+
const count = 5;
42+
const repeatedStr = repeatStr(str, count);
43+
expect(repeatedStr).toEqual("byebyebyebyebye");
44+
});
45+
1946
// Case: handle count of 1:
2047
// Given a target string `str` and a `count` equal to 1,
2148
// When the repeatStr function is called with these inputs,
22-
// Then it should return the original `str` without repetition.
2349

2450
// Case: Handle count of 0:
2551
// Given a target string `str` and a `count` equal to 0,

0 commit comments

Comments
 (0)