Skip to content

Commit cf3dfcc

Browse files
committed
Repeat string: added test cases, added function logic, all tests pass
1 parent 94abcfd commit cf3dfcc

2 files changed

Lines changed: 31 additions & 5 deletions

File tree

‎practice-tdd/repeat-str.js‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
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 repeatedString = "";
3+
if (count < 0) {
4+
throw new Error("Please enter a non-negative number");
5+
}
6+
else if (count === 0){
7+
return ""
8+
}
9+
else if (count === 1) {
10+
return str
11+
}
12+
for (i = 0; i < count; i++) {
13+
repeatedString += str
14+
15+
}
16+
return repeatedString
517
}

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,27 @@ 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 1 time", () => {
24+
const str = "hello";
25+
const count = 1;
26+
const repeatedStr = repeatStr(str, count);
27+
expect(repeatedStr).toEqual("hello");
28+
});
2329

2430
// Case: Handle count of 0:
2531
// Given a target string `str` and a `count` equal to 0,
2632
// When the repeatStr function is called with these inputs,
2733
// Then it should return an empty string.
28-
34+
test("should repeat the string 0 times, returns empty str", () => {
35+
const str = "hello";
36+
const count = 0;
37+
const repeatedStr = repeatStr(str, count);
38+
expect(repeatedStr).toEqual("");
39+
});
2940
// Case: Handle negative count:
3041
// Given a target string `str` and a negative integer `count`,
3142
// When the repeatStr function is called with these inputs,
3243
// Then it should throw an error, as negative counts are not valid.
44+
test("negative count: throws an error as negative counts are not valid", () => {
45+
expect(() => repeatStr("hello", -1)).toThrow("Please enter a non-negative number");
46+
});

0 commit comments

Comments
 (0)