skip to Main Content

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


  1. 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:

    export const Language = {
      enUS: 1,
      zhHant: 2
    } as const;
    
    
    Login or Signup to reply.
  2. 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:

    enum Language {
      enUS = 1,
      zhHant = 2
    };
    
    console.log(Language)
    /* {
      "1": "enUS",
      "2": "zhHant",
      "enUS": 1,
      "zhHant": 2
    }  */
    

    So to get "enUS" from 1, all you need to do is write Language[1]:

    console.log(Language[1]) // "enUS"
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search