Skip to content

Commit d7628a7

Browse files
committed
Add repeatStr tests and implementation using tdd
1 parent 1cce0d0 commit d7628a7

2 files changed

Lines changed: 38 additions & 4 deletions

File tree

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,26 @@
1-
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+
/**
2+
* Repeats a string a given number of times.
3+
* This re-implements String.prototype.repeat without using it.
4+
*
5+
* @param {string} str - The string to repeat.
6+
* @param {number} count - How many times to repeat it. Must be 0 or greater.
7+
* @returns {string} The string repeated count times, or "" if count is 0.
8+
* @throws {Error} If count is negative.
9+
*
10+
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
11+
*/
12+
function repeatStr(str, count) {
13+
if (count < 0) {
14+
throw new Error("count must be 0 or greater");
15+
}
16+
17+
let result = "";
18+
19+
for (let i = 1; i < count; i++) {
20+
result = result + str;
21+
}
22+
23+
return result;
524
}
625

726
module.exports = repeatStr;

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,28 @@ 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 return the original string when count is 1", () => {
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.
34+
test("should return an empty string when count is 0", () => {
35+
const str = "hello";
36+
const count = 0;
37+
const repeatedStr = repeatStr(str, count);
38+
expect(repeatedStr).toEqual("");
39+
});
2840

2941
// Case: Handle negative count:
3042
// Given a target string `str` and a negative integer `count`,
3143
// When the repeatStr function is called with these inputs,
3244
// Then it should throw an error, as negative counts are not valid.
45+
test("should throw an error when count is negative", () => {
46+
expect(() => repeatStr("hello", -1)).toThrow();
47+
});

0 commit comments

Comments
 (0)