diff --git a/String/RepeatString.js b/String/RepeatString.js new file mode 100644 index 0000000000..513f9d7c99 --- /dev/null +++ b/String/RepeatString.js @@ -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 } diff --git a/String/test/RepeatString.test.js b/String/test/RepeatString.test.js new file mode 100644 index 0000000000..86c40b03bc --- /dev/null +++ b/String/test/RepeatString.test.js @@ -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) + }) +})