I have an enum:
export enum Language {
enUS = 1,
zhHant = 2
};
I want a function that can efficiently get me the key based on the value passed:
export enum Language {
enUS = 1,
zhHant = 2
};
const languageMap = new Map<number, Language>(
Object.entries(Language).map(([key, value]) => [parseInt(key), value as Language])
);
const mapLanguage = (languageCode = 1): Language | null => {
return languageMap.get(languageCode) || null;
};
What is the most performant way because imagine this method is used against a million entries? Is it to use Map and Map.get()?
2
Answers
The "key" is a named symbol that only exists in TypeScript. If you want to have a key/value pair construct, you should use either a Map or an object record:
Numeric enums in TypeScript are automatically supplied with reverse mappings. That is, the enum will also contain numeric keys that go to string values. All you have to do to get a key from the value is to index into the enum object with the value. Observe that your
Language
enum compiles to something like this:So to get
"enUS"
from1
, all you need to do is writeLanguage[1]
:This means you really don’t have to write a function to do this, since it’s essentially just an indexing operation.
As for performance, it’s not clear how best to measure that, so I’m not going to attempt to answer that. Depending on use cases,
Map
operations can be faster than the equivalent object operations. But the only way for you to know is to actually run some tests and then only think about changing the implementation if you hit a performance bottleneck. If object lookups are too slow for your use case, you probably have a lot of other problems.Playground link to code