Match on values, not keys, duh

This commit is contained in:
Markus Olsson 2020-11-24 13:52:06 +01:00
parent d5cb23e64f
commit beafeb3fb5

View file

@ -1,3 +1,7 @@
type StringEnum<T extends string> = {
[key: string]: T
}
/**
* Parse a string into the given (string) enum type. Returns undefined if the
* enum type provided did not match any of the keys in the enum.
@ -6,13 +10,16 @@
* one-liner. I measured it and this is 200x faster and doesn't allocate any
* unnecessary arrays.
*/
export function parseEnumValue<T>(
enumObj: Record<string, T>,
key: string
export function parseEnumValue<T extends string>(
enumObj: StringEnum<T>,
value: string
): T | undefined {
for (const k in enumObj) {
if (k === key && Object.prototype.hasOwnProperty.call(enumObj, k)) {
return enumObj[k]
for (const key in enumObj) {
if (
Object.prototype.hasOwnProperty.call(enumObj, key) &&
enumObj[key] === value
) {
return enumObj[key]
}
}
return undefined