Skip to content

Commit

Permalink
fix randomParagraph
Browse files Browse the repository at this point in the history
  • Loading branch information
narcis-fv committed Sep 28, 2023
1 parent d97f8ae commit e40b752
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
22 changes: 22 additions & 0 deletions src/random/randomParagraph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
20 changes: 18 additions & 2 deletions src/random/randomParagraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) + "."
);
};

0 comments on commit e40b752

Please sign in to comment.