Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: lorem null response fix #1407

Merged
merged 10 commits into from
Oct 9, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 26 additions & 11 deletions src/modules/lorem/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Faker } from '../..';
import { filterWordListByLength } from '../word/filterWordListByLength';

/**
* Module to generate random texts and words.
Expand All @@ -17,24 +18,38 @@ 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.
* 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.
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
*
* @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. Defaults to 'any-length'.
*
* @example
* faker.lorem.word() // 'temporibus'
* faker.lorem.word(5) // 'velit'
*
* @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 {
return this.faker.helpers.arrayElement(
filterWordListByLength({
...(typeof options === 'number' ? { length: options } : options),
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
wordList: this.faker.definitions.lorem.words,
})
);
}

/**
Expand Down
100 changes: 100 additions & 0 deletions src/modules/word/filterWordListByLength.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { FakerError } from '../../errors/faker-error';

/**
* The error handling strategies for the `filterWordListByLength` function.
*
* Always returns a new array.
*/
const strategies = {
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
fail: () => {
throw new FakerError('No words found that match the given length.');
},
closest: (
wordList: string[],
length: { min: number; max: number }
): string[] => {
const wordsByLength = wordList.reduce((data, word) => {
data[word.length] = data[word.length] || [];
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
data[word.length].push(word);
return data;
}, {} as Record<number, string[]>);

const min = Math.min(...Object.keys(wordsByLength).map(Number));
const max = Math.max(...Object.keys(wordsByLength).map(Number));
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved

const closestOffset = Math.min(length.min - min, max - length.max);

return wordList.filter(
(word) =>
word.length === length.min - closestOffset ||
word.length === length.max + closestOffset
);
},
shortest: (wordList: string[]): string[] => {
return wordList.filter(
(word) => word.length === Math.min(...wordList.map((word) => word.length))
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
);
},
longest: (wordList: string[]): string[] => {
return wordList.filter(
(word) => word.length === Math.max(...wordList.map((word) => word.length))
);
},
'any-length': (wordList: string[]): string[] => {
return [...wordList];
},
} as const; /*
satisfies Record<
string, // Parameters<filterWordListByLength>[0]['strategy']
(wordList: string[], length: { min: number; max: number }) => string[]
>;
*/

/**
* Filters a string array for values with a matching length.
* If length is not provided or no values with a matching length are found,
* then the result will be determined using the given error handling strategy.
*
* 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 copy of the original word list.
*
* @param options The options to provide.
* @param options.wordList A list of words to filter.
* @param options.length The exact or the range of lengths the words should have.
* @param options.strategy The strategy to apply when no words with a matching length are found. Defaults to 'any-length'.
*/
export function filterWordListByLength(options: {
wordList: string[];
length?: number | { min: number; max: number };
strategy?: 'fail' | 'closest' | 'shortest' | 'longest' | 'any-length';
}): string[] {
const { wordList, length, strategy = 'any-length' } = options;

if (length) {
const filter: (word: string) => boolean =
typeof length === 'number'
? (word) => word.length === length
: (word) => word.length >= length.min && word.length <= length.max;

const wordListWithLengthFilter = wordList.filter(filter);

if (wordListWithLengthFilter.length > 0) {
return wordListWithLengthFilter;
}

if (typeof length === 'number') {
return strategies[strategy](wordList, { min: length, max: length });
} else {
return strategies[strategy](wordList, length);
}
} else if (strategy === 'shortest' || strategy === 'longest') {
return strategies[strategy](wordList);
} else {
return [...wordList];
}
}
Loading