Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/lib/enum.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,14 @@ describe("enum tests", () => {
const values = getEnumValues<TestEnum>(TestEnum);
expect(values).toStrictEqual([TestEnum.A, TestEnum.B, TestEnum.C]);
});

test("getEnumNames/getEnumValues with empty enum", () => {
enum TestEnum {}

const names = getEnumNames<TestEnum>(TestEnum);
expect(names).toStrictEqual([]);

const values = getEnumValues<TestEnum>(TestEnum);
expect(values).toStrictEqual([]);
});
});
17 changes: 12 additions & 5 deletions src/lib/enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ export type StandardEnum<T> = {
* @returns A string containing the name of the enum
*/
export function getEnumNameFromValue<T>(enumVariable: StandardEnum<T>, enumValue: T): string {
return Object.keys(enumVariable)[Object.values(enumVariable).findIndex((x) => x === enumValue)];
let result = enumVariable[enumValue as keyof StandardEnum<T>] as string;

if (result === undefined && isEnumString(enumVariable)) {
result = Object.keys(enumVariable)[Object.values(enumVariable).indexOf(enumValue)];
}

return result;
}

/**
Expand All @@ -23,8 +29,7 @@ export function getEnumNameFromValue<T>(enumVariable: StandardEnum<T>, enumValue
* @returns A string containing the value of the enum
*/
export function getEnumValueFromName<T>(enumVariable: StandardEnum<T>, 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<T>] as T;
}

/**
Expand Down Expand Up @@ -59,7 +64,9 @@ export function getEnumValues<T>(enumVariable: StandardEnum<T>): T[] {
* @returns A bool
*/
function isEnumString<T>(enumVariable: StandardEnum<T>) {
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;
}