From a2288eeefa6bd4b7612da80fa6c8b0e6c87115de Mon Sep 17 00:00:00 2001 From: Kir_Antipov Date: Fri, 20 Jan 2023 12:13:25 +0000 Subject: [PATCH] Made a function to retrieve enum entries --- src/utils/enum/enum-entry.ts | 27 +++++++++++++++++ tests/unit/utils/enum/enum-entry.spec.ts | 38 ++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 src/utils/enum/enum-entry.ts create mode 100644 tests/unit/utils/enum/enum-entry.spec.ts diff --git a/src/utils/enum/enum-entry.ts b/src/utils/enum/enum-entry.ts new file mode 100644 index 0000000..024405e --- /dev/null +++ b/src/utils/enum/enum-entry.ts @@ -0,0 +1,27 @@ +import { isReadOnlyMap } from "@/utils/collections"; +import { EnumKey, enumKeys } from "./enum-key"; +import { EnumValue } from "./enum-value"; + +/** + * Represents an entry in an enum, where the first element is the key and the second element is the value. + * + * @template T - Type of the enum. + */ +export type EnumEntry = [EnumKey, EnumValue]; + +/** + * Retrieves an array of the entries of the specified `enum` object. + * + * @template T - Type of the enum. + * + * @param e - The enum object to retrieve the entries for. + * + * @returns An array of the entries of the specified `enum` object. + */ +export function enumEntries(e: T): [EnumKey, EnumValue][] { + if (isReadOnlyMap, EnumValue>(e)) { + return [...e.entries()]; + } + + return enumKeys(e).map(key => [key, e[key]]); +} diff --git a/tests/unit/utils/enum/enum-entry.spec.ts b/tests/unit/utils/enum/enum-entry.spec.ts new file mode 100644 index 0000000..7a6df2a --- /dev/null +++ b/tests/unit/utils/enum/enum-entry.spec.ts @@ -0,0 +1,38 @@ +import { Enum } from "@/utils/enum/enum"; +import { enumEntries } from "@/utils/enum/enum-entry"; + +describe("enumEntries", () => { + test("returns the correct entries for number-based built-in enums", () => { + enum NumberEnum { + A = 1, + B = 2, + C = 3, + } + + const entries = enumEntries(NumberEnum); + + expect(entries).toEqual([["A", 1], ["B", 2], ["C", 3]]); + }); + + test("returns the correct entries for string-based built-in enums", () => { + enum StringEnum { + A = "a", + B = "b", + C = "c", + } + + const entries = enumEntries(StringEnum); + expect(entries).toEqual([["A", "a"], ["B", "b"], ["C", "c"]]); + }); + + test("returns the correct entries for custom enums created with Enum.create", () => { + const CustomEnum = Enum.create({ + A: 1n, + B: 2n, + C: 3n, + }); + + const entries = enumEntries(CustomEnum); + expect(entries).toEqual([["A", 1n], ["B", 2n], ["C", 3n]]); + }); +});