From e40b752ec8aaf0eb8c272d278c09c29ef0a038b2 Mon Sep 17 00:00:00 2001 From: narcis-fv Date: Thu, 28 Sep 2023 12:56:27 +0100 Subject: [PATCH] fix randomParagraph --- src/random/randomParagraph.test.ts | 22 ++++++++++++++++++++++ src/random/randomParagraph.ts | 20 ++++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/random/randomParagraph.test.ts b/src/random/randomParagraph.test.ts index d80478e..4acac33 100644 --- a/src/random/randomParagraph.test.ts +++ b/src/random/randomParagraph.test.ts @@ -8,3 +8,25 @@ describe(`randomParagraph`, () => { expect(randomParagraph().endsWith(".")).toBeTruthy(); }); }); + +it(`respects maxCharacters`, () => { + const result = randomParagraph({ maxCharacters: 10 }); + expect(result.length).toBeLessThanOrEqual(10); +}); + +it(`respects words count with a large enough maxCharacters`, () => { + const result = randomParagraph({ words: 5, maxCharacters: 1000 }); + const wordCount = result.split(" ").length; + // Subtracting 1 because the last word is followed by a period. + expect(wordCount).toEqual(5); +}); + +it(`does not exceed maxCharacters even with large words count`, () => { + const result = randomParagraph({ maxCharacters: 10, words: 10 }); + expect(result.length).toBeLessThanOrEqual(10); +}); + +it(`returns a string with a period at the end`, () => { + const result = randomParagraph(); + expect(result.endsWith(".")).toBeTruthy(); +}); diff --git a/src/random/randomParagraph.ts b/src/random/randomParagraph.ts index 5b00e82..8924bf7 100644 --- a/src/random/randomParagraph.ts +++ b/src/random/randomParagraph.ts @@ -2,6 +2,22 @@ import { array } from "../helpers"; import { capitalize } from "../helpers/capitalize"; import { randomWord } from "./randomWord"; -export const randomParagraph = () => { - return capitalize(array(8, () => randomWord()).join(" ")) + "."; +/** + * Generates a random paragraph of text. + * @param maxCharacters The maximum number of characters. The paragraph will be truncated to this length if it exceeds it. Default is 200. + * @param words The number of words. Default is 8. + * @returns A random paragraph of text. + */ +export const randomParagraph = ({ + maxCharacters = 200, + words = 8, +}: { + maxCharacters?: number; + words?: number; +} = {}) => { + return capitalize( + array(words, () => randomWord()) + .join(" ") + .slice(0, maxCharacters - 1) + "." + ); };