The in operator narrowing in Typescript - Time & Space Complexity
We want to see how using the in operator affects the time it takes for a program to run.
Specifically, how checking if a property exists in an object changes the work done as input grows.
Analyze the time complexity of the following code snippet.
function process(input: object, keys: string[]) {
for (const key of keys) {
if (key in input) {
console.log(`Found key: ${key}`);
}
}
}
This code checks each key in an array to see if it exists in the given object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the
keysarray and checkingkey in input. - How many times: Once for each key in the
keysarray.
Each key check takes about the same time, so total work grows as the number of keys grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 property checks |
| 100 | About 100 property checks |
| 1000 | About 1000 property checks |
Pattern observation: The work increases directly with the number of keys checked.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the number of keys grows.
[X] Wrong: "Checking if a key exists with in takes longer for bigger objects."
[OK] Correct: Property checks with in are very fast and do not depend on object size because objects use fast lookup methods internally.
Understanding how property checks scale helps you reason about code efficiency and write better programs.
"What if we replaced the object with a nested object and checked keys deeply? How would the time complexity change?"