Exhaustive pattern matching in Typescript - Time & Space Complexity
We want to understand how the time it takes to run exhaustive pattern matching changes as the number of cases grows.
How does checking all possible patterns affect the program's speed?
Analyze the time complexity of the following code snippet.
function describeValue(value: string | number | boolean) {
return match(value) {
case (v: string) => `String: ${v}`,
case (v: number) => `Number: ${v}`,
case (v: boolean) => `Boolean: ${v}`,
};
}
This code checks the type of the input and returns a description for each possible type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each pattern case one by one.
- How many times: Once per case until a match is found.
As the number of patterns increases, the program checks more cases in order.
| Input Size (number of cases) | Approx. Operations (checks) |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of cases.
Time Complexity: O(n)
This means the time to find a matching case grows linearly with the number of patterns.
[X] Wrong: "Exhaustive pattern matching checks all cases every time, no matter what."
[OK] Correct: The matching stops as soon as a case fits, so it often checks fewer cases than the total.
Understanding how pattern matching scales helps you explain code efficiency clearly and shows you can reason about control flow in real projects.
"What if the patterns were nested or involved recursive structures? How would that affect the time complexity?"