Global augmentation in Typescript - Time & Space Complexity
We want to understand how adding new properties or methods to existing types affects the speed of our program.
How does this change the work the program does as input grows?
Analyze the time complexity of the following code snippet.
// Add a new method to the Array type
declare global {
interface Array {
doubleLength(): number;
}
}
Array.prototype.doubleLength = function() {
return this.length * 2;
};
const arr = [1, 2, 3];
console.log(arr.doubleLength());
This code adds a new method to all arrays that returns twice their length.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the array's length property.
- How many times: Once per method call, no loops or recursion involved.
Since the method only reads the length property and multiplies it, the work stays the same no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 simple operation |
| 100 | 1 simple operation |
| 1000 | 1 simple operation |
Pattern observation: The work does not increase as the array grows.
Time Complexity: O(1)
This means the method runs in constant time regardless of the array size.
[X] Wrong: "Adding a method to Array makes all array operations slower because it loops over elements."
[OK] Correct: The added method runs only when called, and if it does not loop, it does not slow down other array operations.
Understanding how extending built-in types affects performance shows you can think about code design and efficiency together.
"What if the new method loops through all array elements? How would the time complexity change?"