From 003f5fbab409f1c1c30fe861fa138e00ffdbc869 Mon Sep 17 00:00:00 2001 From: Kir_Antipov Date: Fri, 20 Jan 2023 11:58:32 +0000 Subject: [PATCH] Made a function to retrieve enum values --- src/utils/enum/enum-value.ts | 26 ++++++++++++++++ tests/unit/utils/enum/enum-value.spec.ts | 38 ++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/utils/enum/enum-value.ts create mode 100644 tests/unit/utils/enum/enum-value.spec.ts diff --git a/src/utils/enum/enum-value.ts b/src/utils/enum/enum-value.ts new file mode 100644 index 0000000..9344fdf --- /dev/null +++ b/src/utils/enum/enum-value.ts @@ -0,0 +1,26 @@ +import { isReadOnlyMap } from "@/utils/collections"; +import { EnumKey, enumKeys } from "./enum-key"; + +/** + * Extracts the type of values stored in an enum. + * + * @template T - The type of the enum. + */ +export type EnumValue = T[keyof T]; + +/** + * Retrieves an array of the values of the specified `enum` object. + * + * @template T - Type of the enum. + * + * @param e - The enum object to retrieve the values for. + * + * @returns An array of the values of the specified `enum` object. + */ +export function enumValues(e: T): EnumValue[] { + if (isReadOnlyMap, EnumValue>(e)) { + return [...e.values()]; + } + + return enumKeys(e).map(key => e[key]); +} diff --git a/tests/unit/utils/enum/enum-value.spec.ts b/tests/unit/utils/enum/enum-value.spec.ts new file mode 100644 index 0000000..524c10a --- /dev/null +++ b/tests/unit/utils/enum/enum-value.spec.ts @@ -0,0 +1,38 @@ +import { Enum } from "@/utils/enum/enum"; +import { enumValues } from "@/utils/enum/enum-value"; + +describe("enumValues", () => { + test("returns the correct values for number-based built-in enums", () => { + enum NumberEnum { + A = 1, + B = 2, + C = 3, + } + + const values = enumValues(NumberEnum); + + expect(values).toEqual([1, 2, 3]); + }); + + test("returns the correct values for string-based built-in enums", () => { + enum StringEnum { + A = "a", + B = "b", + C = "c", + } + + const values = enumValues(StringEnum); + expect(values).toEqual(["a", "b", "c"]); + }); + + test("returns the correct values for custom enums created with Enum.create", () => { + const CustomEnum = Enum.create({ + A: 1n, + B: 2n, + C: 3n, + }); + + const values = enumValues(CustomEnum); + expect(values).toEqual([1n, 2n, 3n]); + }); +});