diff options
| author | Caio Borghi <[email protected]> | 2023-03-15 13:35:50 -0300 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-03-15 17:35:50 +0100 |
| commit | f2abf8b49439fc3c6197ecc9a16e212c9e64497a (patch) | |
| tree | 1560288013b5c448245b95eaa212647cf5027574 /src/modules | |
| parent | e5442d2a9cb38e6f69da3a9206ea62b64862ef31 (diff) | |
| download | faker-f2abf8b49439fc3c6197ecc9a16e212c9e64497a.tar.xz faker-f2abf8b49439fc3c6197ecc9a16e212c9e64497a.zip | |
feat(helpers): new method enumValue (#1920)
Co-authored-by: ST-DDT <[email protected]>
Diffstat (limited to 'src/modules')
| -rw-r--r-- | src/modules/helpers/index.ts | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/modules/helpers/index.ts b/src/modules/helpers/index.ts index 4f1c164d..b3d4bce9 100644 --- a/src/modules/helpers/index.ts +++ b/src/modules/helpers/index.ts @@ -623,6 +623,37 @@ export class HelpersModule { } /** + * Returns a random value from an Enum object. + * + * This does the same as `objectValue` except that it ignores (the values assigned to) the numeric keys added for TypeScript enums. + * + * @template EnumType Type of generic enums, automatically inferred by TypeScript. + * @param enumObject Enum to pick the value from. + * + * @example + * enum Color { Red, Green, Blue } + * faker.helpers.enumValue(Color) // 1 (Green) + * + * enum Direction { North = 'North', South = 'South'} + * faker.helpers.enumValue(Direction) // 'South' + * + * enum HttpStatus { Ok = 200, Created = 201, BadRequest = 400, Unauthorized = 401 } + * faker.helpers.enumValue(HttpStatus) // 200 (Ok) + * + * @since 8.0.0 + */ + enumValue<EnumType extends Record<string | number, string | number>>( + enumObject: EnumType + ): EnumType[keyof EnumType] { + // ignore numeric keys added by TypeScript + const keys: Array<keyof EnumType> = Object.keys(enumObject).filter((key) => + isNaN(Number(key)) + ); + const randomKey = this.arrayElement(keys); + return enumObject[randomKey]; + } + + /** * Generator for combining faker methods based on a static string input. * * Note: We recommend using string template literals instead of `fake()`, |
