Skip to content

Commit 2447e03

Browse files
feat: add string repeat algorithm
1 parent 5c39e87 commit 2447e03

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

‎String/RepeatString.js‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @function repeatString
3+
* @description Repeats a string a specified number of times
4+
* without using JavaScript's built-in String.repeat().
5+
* @param {string} str - The input string to repeat
6+
* @param {number} n - Number of times to repeat
7+
* @returns {string} - The repeated string
8+
* @see https://en.wikipedia.org/wiki/String_(computer_science)
9+
* @example repeatString("abc", 3) => "abcabcabc"
10+
* @example repeatString("ha", 2) => "haha"
11+
* @example repeatString("abc", 0) => ""
12+
*/
13+
const repeatString = (str, n) => {
14+
if (typeof str !== 'string') {
15+
throw new TypeError('First argument must be a string')
16+
}
17+
if (!Number.isInteger(n) || n < 0) {
18+
throw new TypeError('Second argument must be a non-negative integer')
19+
}
20+
let result = ''
21+
for (let i = 0; i < n; i++) {
22+
result += str
23+
}
24+
return result
25+
}
26+
27+
export { repeatString }

‎String/test/RepeatString.test.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { repeatString } from '../RepeatString.js'
2+
3+
describe('repeatString', () => {
4+
test("repeatString('abc', 3) returns 'abcabcabc'", () => {
5+
expect(repeatString('abc', 3)).toBe('abcabcabc')
6+
})
7+
8+
test("repeatString('ha', 2) returns 'haha'", () => {
9+
expect(repeatString('ha', 2)).toBe('haha')
10+
})
11+
12+
test("repeatString('abc', 0) returns ''", () => {
13+
expect(repeatString('abc', 0)).toBe('')
14+
})
15+
16+
test("repeatString('abc', 1) returns 'abc'", () => {
17+
expect(repeatString('abc', 1)).toBe('abc')
18+
})
19+
20+
test('repeatString empty string returns empty string', () => {
21+
expect(repeatString('', 5)).toBe('')
22+
})
23+
24+
test('repeatString single char', () => {
25+
expect(repeatString('a', 5)).toBe('aaaaa')
26+
})
27+
28+
test('repeatString with spaces', () => {
29+
expect(repeatString('ab ', 3)).toBe('ab ab ab ')
30+
})
31+
32+
test('throws TypeError for non-string input', () => {
33+
expect(() => repeatString(123, 3)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative n', () => {
37+
expect(() => repeatString('abc', -1)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float n', () => {
41+
expect(() => repeatString('abc', 1.5)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)