Heterogeneous enums in Typescript - Time & Space Complexity
We want to understand how the time needed to use heterogeneous enums changes as the enum size grows.
Specifically, how does accessing or searching enum values behave when enums mix strings and numbers?
Analyze the time complexity of the following code snippet.
enum MixedEnum {
No = 0,
Yes = 1,
Maybe = 2,
Later = "later"
}
function isValueInEnum(value: string | number): boolean {
return Object.values(MixedEnum).includes(value);
}
This code defines a heterogeneous enum with both numbers and strings, then checks if a value exists in it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The call to
Object.values(MixedEnum)creates an array of enum values, thenincludeschecks each element one by one. - How many times: The
includesmethod may check up to all enum values, so it runs once per enum value.
As the enum gets bigger, the number of checks grows directly with the number of enum values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The time grows in a straight line with the number of enum values.
Time Complexity: O(n)
This means the time to check a value grows directly with the number of enum entries.
[X] Wrong: "Checking if a value is in an enum is always instant, no matter the size."
[OK] Correct: Because includes checks each value one by one, bigger enums take longer to search.
Understanding how enum lookups scale helps you write efficient code and explain your reasoning clearly in interviews.
What if we stored enum values in a Set instead of an array? How would the time complexity change?