From a6ce71703b02f7c2c4f742106acff05d879c4384 Mon Sep 17 00:00:00 2001 From: ST-DDT Date: Sun, 9 Oct 2022 21:26:25 +0200 Subject: feat: lorem null response fix (#1407) --- src/modules/lorem/index.ts | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) (limited to 'src/modules/lorem') diff --git a/src/modules/lorem/index.ts b/src/modules/lorem/index.ts index 4745b0e9..ac1ba756 100644 --- a/src/modules/lorem/index.ts +++ b/src/modules/lorem/index.ts @@ -1,4 +1,5 @@ import type { Faker } from '../..'; +import { filterWordListByLength } from '../word/filterWordListByLength'; /** * Module to generate random texts and words. @@ -17,24 +18,43 @@ export class LoremModule { /** * Generates a word of a specified length. * - * @param length length of the word that should be returned. Defaults to a random length. + * @param options The expected length of the word or the options to use. + * @param options.length The expected length of the word. + * @param options.strategy The strategy to apply when no words with a matching length are found. + * + * Available error handling strategies: + * + * - `fail`: Throws an error if no words with the given length are found. + * - `shortest`: Returns any of the shortest words. + * - `closest`: Returns any of the words closest to the given length. + * - `longest`: Returns any of the longest words. + * - `any-length`: Returns a word with any length. + * + * Defaults to `'any-length'`. * * @example * faker.lorem.word() // 'temporibus' * faker.lorem.word(5) // 'velit' + * faker.lorem.word({ strategy: 'shortest' }) // 'a' + * faker.lorem.word({ length: { min: 5, max: 7 }, strategy: "fail" }) // 'quaerat' * * @since 3.1.0 */ - word(length?: number): string { - const hasRightLength = (word: string) => word.length === length; - let properLengthWords: readonly string[]; - if (length == null) { - properLengthWords = this.faker.definitions.lorem.words; - } else { - properLengthWords = - this.faker.definitions.lorem.words.filter(hasRightLength); - } - return this.faker.helpers.arrayElement(properLengthWords); + word( + options: + | number + | { + length?: number | { min: number; max: number }; + strategy?: 'fail' | 'closest' | 'shortest' | 'longest' | 'any-length'; + } = {} + ): string { + const opts = typeof options === 'number' ? { length: options } : options; + return this.faker.helpers.arrayElement( + filterWordListByLength({ + ...opts, + wordList: this.faker.definitions.lorem.words, + }) + ); } /** -- cgit v1.2.3