mirror of
https://github.com/Kir-Antipov/mc-publish.git
synced 2024-11-22 08:20:58 -05:00
Made a function to retrieve enum entries
This commit is contained in:
parent
003f5fbab4
commit
a2288eeefa
2 changed files with 65 additions and 0 deletions
27
src/utils/enum/enum-entry.ts
Normal file
27
src/utils/enum/enum-entry.ts
Normal 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]]);
|
||||
}
|
38
tests/unit/utils/enum/enum-entry.spec.ts
Normal file
38
tests/unit/utils/enum/enum-entry.spec.ts
Normal 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]]);
|
||||
});
|
||||
});
|
Loading…
Reference in a new issue