diff --git a/README.md b/README.md index acdeaa0..79f7cde 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ const { length } = require("light-string-utils"); - [`limit()`](#limit) - [`occurance()`](#occurance) - [`pad()`](#pad) +- [`repeat()`](#repeat) - [`replaceBy()`](#replaceBy) - [`sentenceCase()`](#sentenceCase) - [`slugify()`](#slugify) @@ -411,6 +412,30 @@ pad("Hello World", "both", "!!!"); // Returns "!!!Hello World!!!" pad("Hello World", "both"); // Returns "Hello World" ``` +## repeat + +repeats a string by defined times. + + +### Parameters + +| Name | Type | Default | Description | +| ---- | ---- | ------- | ----------- | +| item | {item} | _none_ | The input string/number to be repeated. | +| times | {number} | 1 | The number of times to repeat the string. | +| delimiter | {string} | "" | The delimiter to be used between the repeated strings. | +### Returns + +{string} - The repeated string. + +### Examples + +```js +repeat("san"); // Returns "san" +repeat("san", 4); // Returns "sansansansan" +repeat("test ", 2); // Returns "test test" +``` + ## replaceBy Replaces all the occurrences of a string with another string. diff --git a/src/repeat/index.js b/src/repeat/index.js new file mode 100644 index 0000000..35df8cc --- /dev/null +++ b/src/repeat/index.js @@ -0,0 +1,23 @@ +/** + +@name repeat +@description repeats a string by defined times. +@param {item} item - _none_ - The input string/number to be repeated. +@param {number} times - 1 - The number of times to repeat the string. +@param {string} delimiter - "" - The delimiter to be used between the repeated strings. +@returns {string} - The repeated string. +@throws {Error} - Throws an error if the input is not a string. +@example repeat("san"); // Returns "san" +@example repeat("san", 4); // Returns "sansansansan" +@example repeat("test ", 2); // Returns "test test" +*/ + +function repeat(item, times = 1, delimiter = "") { + if (!item) { + throw new Error("Invalid string served"); + } + + return new Array(times).fill(item).join(delimiter); +} + +module.exports = repeat; diff --git a/src/repeat/index.test.js b/src/repeat/index.test.js new file mode 100644 index 0000000..d4d0dbc --- /dev/null +++ b/src/repeat/index.test.js @@ -0,0 +1,14 @@ +const repeat = require("./index"); + +describe("repeat()", () => { + test("Test that the function throws an error if an invalid input is provided", () => { + expect(() => repeat(null)).toThrow(Error); + expect(() => repeat(undefined)).toThrow(Error); + }); + + test("Test that the function correctly repeats a single word", () => { + expect(repeat("test")).toBe("test"); + expect(repeat("testing", 2)).toBe("testingtesting"); + expect(repeat("testing", 2, " ")).toBe("testing testing"); + }); +});