From f2abf8b49439fc3c6197ecc9a16e212c9e64497a Mon Sep 17 00:00:00 2001 From: Caio Borghi Date: Wed, 15 Mar 2023 13:35:50 -0300 Subject: feat(helpers): new method enumValue (#1920) Co-authored-by: ST-DDT --- src/modules/helpers/index.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'src') 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 @@ -622,6 +622,37 @@ export class HelpersModule { return arrayCopy.slice(min); } + /** + * 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>( + enumObject: EnumType + ): EnumType[keyof EnumType] { + // ignore numeric keys added by TypeScript + const keys: Array = 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. * -- cgit v1.2.3