Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions String/RepeatString.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @function repeatString
* @description Repeats a string a specified number of times
* without using JavaScript's built-in String.repeat().
* @param {string} str - The input string to repeat
* @param {number} n - Number of times to repeat
* @returns {string} - The repeated string
* @see https://en.wikipedia.org/wiki/String_(computer_science)
* @example repeatString("abc", 3) => "abcabcabc"
* @example repeatString("ha", 2) => "haha"
* @example repeatString("abc", 0) => ""
*/
const repeatString = (str, n) => {
if (typeof str !== 'string') {
throw new TypeError('First argument must be a string')
}
if (!Number.isInteger(n) || n < 0) {
throw new TypeError('Second argument must be a non-negative integer')
}
let result = ''
for (let i = 0; i < n; i++) {
result += str
}
return result
}

export { repeatString }
43 changes: 43 additions & 0 deletions String/test/RepeatString.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { repeatString } from '../RepeatString.js'

describe('repeatString', () => {
test("repeatString('abc', 3) returns 'abcabcabc'", () => {
expect(repeatString('abc', 3)).toBe('abcabcabc')
})

test("repeatString('ha', 2) returns 'haha'", () => {
expect(repeatString('ha', 2)).toBe('haha')
})

test("repeatString('abc', 0) returns ''", () => {
expect(repeatString('abc', 0)).toBe('')
})

test("repeatString('abc', 1) returns 'abc'", () => {
expect(repeatString('abc', 1)).toBe('abc')
})

test('repeatString empty string returns empty string', () => {
expect(repeatString('', 5)).toBe('')
})

test('repeatString single char', () => {
expect(repeatString('a', 5)).toBe('aaaaa')
})

test('repeatString with spaces', () => {
expect(repeatString('ab ', 3)).toBe('ab ab ab ')
})

test('throws TypeError for non-string input', () => {
expect(() => repeatString(123, 3)).toThrow(TypeError)
})

test('throws TypeError for negative n', () => {
expect(() => repeatString('abc', -1)).toThrow(TypeError)
})

test('throws TypeError for float n', () => {
expect(() => repeatString('abc', 1.5)).toThrow(TypeError)
})
})
Loading