Made a function to retrieve enum entries

This commit is contained in:
Kir_Antipov 2023-01-20 12:13:25 +00:00
parent 003f5fbab4
commit a2288eeefa
2 changed files with 65 additions and 0 deletions

View file

@ -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<T> = [EnumKey<T>, EnumValue<T>];
/**
* 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<T>(e: T): [EnumKey<T>, EnumValue<T>][] {
if (isReadOnlyMap<EnumKey<T>, EnumValue<T>>(e)) {
return [...e.entries()];
}
return enumKeys(e).map(key => [key, e[key]]);
}

View file

@ -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]]);
});
});