|
| 1 | +/** |
| 2 | + * |
1 | 3 | // Implement a function repeatStr |
2 | 4 | const repeatStr = require("./repeat-str"); |
3 | 5 | // Given a target string `str` and a positive integer `count`, |
@@ -30,3 +32,74 @@ test("should repeat the string count times", () => { |
30 | 32 | // Given a target string `str` and a negative integer `count`, |
31 | 33 | // When the repeatStr function is called with these inputs, |
32 | 34 | // Then it should throw an error, as negative counts are not valid. |
| 35 | +* |
| 36 | +*/ |
| 37 | + |
| 38 | +// repeat-str.test.js |
| 39 | +const repeatStr = require("./repeat-str"); |
| 40 | + |
| 41 | +// Case: handle multiple repetitions |
| 42 | +test("should repeat the string count times", () => { |
| 43 | + const str = "hello"; |
| 44 | + const count = 3; |
| 45 | + const repeatedStr = repeatStr(str, count); |
| 46 | + expect(repeatedStr).toEqual("hellohellohello"); |
| 47 | +}); |
| 48 | + |
| 49 | +// Case: handle count of 1 |
| 50 | +test("should return the original string when count is 1", () => { |
| 51 | + const str = "hello"; |
| 52 | + const count = 1; |
| 53 | + const repeatedStr = repeatStr(str, count); |
| 54 | + expect(repeatedStr).toEqual("hello"); |
| 55 | +}); |
| 56 | + |
| 57 | +// Case: Handle count of 0 |
| 58 | +test("should return an empty string when count is 0", () => { |
| 59 | + const str = "hello"; |
| 60 | + const count = 0; |
| 61 | + const repeatedStr = repeatStr(str, count); |
| 62 | + expect(repeatedStr).toEqual(""); |
| 63 | +}); |
| 64 | + |
| 65 | +// Case: Handle negative count |
| 66 | +test("should throw an error when count is negative", () => { |
| 67 | + const str = "hello"; |
| 68 | + const count = -1; |
| 69 | + |
| 70 | + expect(() => { |
| 71 | + repeatStr(str, count); |
| 72 | + }).toThrow("Count must be a positive integer"); |
| 73 | +}); |
| 74 | + |
| 75 | +// Additional edge cases |
| 76 | +test("should handle empty string input", () => { |
| 77 | + const str = ""; |
| 78 | + const count = 5; |
| 79 | + const repeatedStr = repeatStr(str, count); |
| 80 | + expect(repeatedStr).toEqual(""); |
| 81 | +}); |
| 82 | + |
| 83 | +test("should handle count as a string number", () => { |
| 84 | + const str = "abc"; |
| 85 | + const count = "3"; |
| 86 | + const repeatedStr = repeatStr(str, count); |
| 87 | + expect(repeatedStr).toEqual("abcabcabc"); |
| 88 | +}); |
| 89 | + |
| 90 | +test("should handle decimal count by flooring", () => { |
| 91 | + const str = "xyz"; |
| 92 | + const count = 2.7; |
| 93 | + const repeatedStr = repeatStr(str, count); |
| 94 | + expect(repeatedStr).toEqual("xyzxyz"); |
| 95 | +}); |
| 96 | + |
| 97 | +test("should throw error for non-numeric count", () => { |
| 98 | + const str = "hello"; |
| 99 | + const count = "abc"; |
| 100 | + |
| 101 | + expect(() => { |
| 102 | + repeatStr(str, count); |
| 103 | + }).toThrow("Count must be a number"); |
| 104 | +}); |
| 105 | + |
0 commit comments