diff --git a/CHANGELOG.md b/CHANGELOG.md index 82a5241..a183554 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Split up `CI` workflow into two separate workflows for the comment posting to work for PRs from forks. +### Fixed + +- Improved `getEnumNameFromValue` and `getEnumValueFromName` performance + ## [1.2.1] - 2025-03-18 ### dependabot: \#57 Bump tj-actions/changed-files from 41 to 46 in /.github/workflows diff --git a/src/lib/enum.spec.ts b/src/lib/enum.spec.ts index 7655c76..45472f0 100644 --- a/src/lib/enum.spec.ts +++ b/src/lib/enum.spec.ts @@ -97,4 +97,14 @@ describe("enum tests", () => { const values = getEnumValues(TestEnum); expect(values).toStrictEqual([TestEnum.A, TestEnum.B, TestEnum.C]); }); + + test("getEnumNames/getEnumValues with empty enum", () => { + enum TestEnum {} + + const names = getEnumNames(TestEnum); + expect(names).toStrictEqual([]); + + const values = getEnumValues(TestEnum); + expect(values).toStrictEqual([]); + }); }); diff --git a/src/lib/enum.ts b/src/lib/enum.ts index a253bff..f5a9f36 100644 --- a/src/lib/enum.ts +++ b/src/lib/enum.ts @@ -13,7 +13,13 @@ export type StandardEnum = { * @returns A string containing the name of the enum */ export function getEnumNameFromValue(enumVariable: StandardEnum, enumValue: T): string { - return Object.keys(enumVariable)[Object.values(enumVariable).findIndex((x) => x === enumValue)]; + let result = enumVariable[enumValue as keyof StandardEnum] as string; + + if (result === undefined && isEnumString(enumVariable)) { + result = Object.keys(enumVariable)[Object.values(enumVariable).indexOf(enumValue)]; + } + + return result; } /** @@ -23,8 +29,7 @@ export function getEnumNameFromValue(enumVariable: StandardEnum, enumValue * @returns A string containing the value of the enum */ export function getEnumValueFromName(enumVariable: StandardEnum, enumName: string): T { - const value = Object.values(enumVariable)[Object.keys(enumVariable).findIndex((x) => x === enumName)] as string; - return (isEnumString(enumVariable) ? value : Number.parseInt(value)) as T; + return enumVariable[enumName as keyof StandardEnum] as T; } /** @@ -59,7 +64,9 @@ export function getEnumValues(enumVariable: StandardEnum): T[] { * @returns A bool */ function isEnumString(enumVariable: StandardEnum) { - const keys = Object.keys(enumVariable); + for (const key in enumVariable) { + return !/^\d+$/.test(key); + } - return keys.length > 0 && !/^\d+$/.test(keys.at(0) as string); + return false; }