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 values
This commit is contained in:
parent
1d0d5c6cff
commit
003f5fbab4
2 changed files with 64 additions and 0 deletions
26
src/utils/enum/enum-value.ts
Normal file
26
src/utils/enum/enum-value.ts
Normal file
|
@ -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> = 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<T>(e: T): EnumValue<T>[] {
|
||||
if (isReadOnlyMap<EnumKey<T>, EnumValue<T>>(e)) {
|
||||
return [...e.values()];
|
||||
}
|
||||
|
||||
return enumKeys(e).map(key => e[key]);
|
||||
}
|
38
tests/unit/utils/enum/enum-value.spec.ts
Normal file
38
tests/unit/utils/enum/enum-value.spec.ts
Normal file
|
@ -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]);
|
||||
});
|
||||
});
|
Loading…
Reference in a new issue