Skip to content

Commit 9f0252c

Browse files
committed
Implement repeat-str and add Jest tests
1 parent a156bac commit 9f0252c

2 files changed

Lines changed: 28 additions & 7 deletions

File tree

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
function repeatStr() {
1+
function repeatStr(str, count) {
22
// 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).
33
// The goal is to re-implement that function, not to use it.
4-
return "hellohellohello";
4+
let combinedStr = "";
5+
if (count < 0) throw new Error("Invalid Count");
6+
7+
for (let i = 0; i < count; i++) {
8+
combinedStr += str;
9+
}
10+
return combinedStr;
511
}
612

713
module.exports = repeatStr;

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

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,26 @@ const repeatStr = require("./repeat-str");
99
// When the repeatStr function is called with these inputs,
1010
// Then it should return a string that contains the original `str` repeated `count` times.
1111

12-
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");
12+
describe("repeatStr", () => {
13+
test("repeats string count times when count is greater than 1", () => {
14+
expect(repeatStr("hello", 3)).toEqual("hellohellohello");
15+
});
16+
17+
test("returns original string when count is 1", () => {
18+
expect(repeatStr("hello", 1)).toEqual("hello");
19+
});
20+
21+
test("returns empty string when count is 0", () => {
22+
expect(repeatStr("hello", 0)).toEqual("");
23+
});
24+
25+
test("throws an error when count is negative", () => {
26+
expect(() => repeatStr("hello", -3)).toThrow("Invalid Count");
27+
});
28+
29+
test("returns empty string when the input string is empty", () => {
30+
expect(repeatStr("", 3)).toEqual("");
31+
});
1732
});
1833

1934
// Case: handle count of 1:

0 commit comments

Comments
 (0)