Skip to content

Commit 0f801bb

Browse files
committed
Implement and write tests for Repeat String task
1 parent 831c151 commit 0f801bb

2 files changed

Lines changed: 37 additions & 4 deletions

File tree

‎practice-tdd/repeat-str.js‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
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+
// 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).
2+
// The goal is to re-implement that function, not to use it.#
3+
export function repeatStr(str, count) {
4+
if (Number.isInteger(count) && count < 0) {
5+
throw new Error(`Invalid input`);
6+
}
7+
if (count === 0) {
8+
return "";
9+
}
10+
11+
if (Number.isInteger(count) && count > 0) {
12+
let result = "";
13+
for (let i = 0; i < count; i++) {
14+
result += str;
15+
}
16+
return result;
17+
}
518
}

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,32 @@ test("should repeat the string count times", () => {
2121
// When the repeatStr function is called with these inputs,
2222
// Then it should return the original `str` without repetition.
2323

24+
test("should repeat the string 1 time", () => {
25+
const str = "hello";
26+
const count = 1;
27+
const repeatedStr = repeatStr(str, count);
28+
expect(repeatedStr).toEqual("hello");
29+
});
30+
2431
// Case: Handle count of 0:
2532
// Given a target string `str` and a `count` equal to 0,
2633
// When the repeatStr function is called with these inputs,
2734
// Then it should return an empty string.
2835

36+
test("should repeat the string 0 times", () => {
37+
const str = "hello";
38+
const count = 0;
39+
const repeatedStr = repeatStr(str, count);
40+
expect(repeatedStr).toEqual("");
41+
});
42+
2943
// Case: Handle negative count:
3044
// Given a target string `str` and a negative integer `count`,
3145
// When the repeatStr function is called with these inputs,
3246
// Then it should throw an error, as negative counts are not valid.
47+
48+
test("should throw an error for negative count", () => {
49+
const str = "hello";
50+
const count = -2;
51+
expect(() => repeatStr(str, count)).toThrow("Invalid input");
52+
});

0 commit comments

Comments
 (0)