Add enumValueToKey utility function

This commit is contained in:
NightKev 2025-06-11 05:44:14 -07:00
parent 5632ad70bd
commit 4920d006e8
2 changed files with 24 additions and 2 deletions

View File

@ -29,7 +29,7 @@ import { MoveResult } from "#enums/move-result";
import { getPokemonNameWithAffix } from "#app/messages";
import Overrides from "#app/overrides";
import { BattlePhase } from "#app/phases/battle-phase";
import { NumberHolder } from "#app/utils/common";
import { enumValueToKey, NumberHolder } from "#app/utils/common";
import { AbilityId } from "#enums/ability-id";
import { ArenaTagType } from "#enums/arena-tag-type";
import { BattlerTagType } from "#enums/battler-tag-type";
@ -129,7 +129,7 @@ export class MovePhase extends BattlePhase {
public start(): void {
super.start();
console.log(MoveId[this.move.moveId], MoveUseMode[this.useMode]);
console.log(MoveId[this.move.moveId], enumValueToKey(MoveUseMode, this.useMode));
// Check if move is unusable (e.g. running out of PP due to a mid-turn Spite
// or the user no longer being on field), ending the phase early if not.

View File

@ -611,3 +611,25 @@ export function getShinyDescriptor(variant: Variant): string {
return i18next.t("common:commonShiny");
}
}
/**
* Returns the name of the key that matches the enum [object] value.
* @param input - The enum [object] to check
* @param val - The value to get the key of
* @returns The name of the key with the specified value
* @example
* const thing = {
* one: 1,
* two: 2,
* } as const;
* console.log(enumValueToKey(thing, thing.two)); // output: "two"
* @throws An `Error` if an invalid enum value is passed to the function
*/
export function enumValueToKey<T extends Record<string, string | number>>(input: T, val: T[keyof T]): keyof T {
for (const [key, value] of Object.entries(input)) {
if (val === value) {
return key as keyof T;
}
}
throw new Error(`Invalid value passed to \`enumValueToKey\`! Value: ${val}`);
}