Skip to content

Commit 4bd5c1e

Browse files
committed
TDD: implement repeatStr with tests
1 parent 83db2f1 commit 4bd5c1e

2 files changed

Lines changed: 26 additions & 4 deletions

File tree

‎practice-tdd/repeat-str.js‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
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(string, count) {
2+
let result = "";
3+
if (count < 0) {
4+
throw new Error("wrong input");
5+
}
6+
for (let n = 0; n < count; n++) {
7+
result = result + string;
8+
}
9+
return result;
510
}

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,30 @@ test("should repeat the string count times", () => {
2020
// Given a target string `str` and a `count` equal to 1,
2121
// When the repeatStr function is called with these inputs,
2222
// Then it should return the original `str` without repetition.
23+
test("should repeat the string one time", () => {
24+
const str = "javascript";
25+
const count = 1;
26+
const repeatedStr = repeatStr(str, count);
27+
expect(repeatedStr).toEqual("javascript");
28+
});
29+
2330

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.
35+
test("should repeat the string 0 times", () => {
36+
const str = "Hi there";
37+
const count = 0;
38+
const repeatedStr = repeatStr(str, count);
39+
expect(repeatedStr).toEqual("");
40+
});
41+
2842

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+
test("should throw an error with negative count times", () => {
48+
expect(() => repeatStr("hello", -5)).toThrow("wrong input");
49+
});

0 commit comments

Comments
 (0)