Migrating JavaScript to TypeScript - Time & Space Complexity
When moving code from JavaScript to TypeScript, it's important to understand how the added type checks affect the program's speed.
We want to see how the program's running time changes as the input grows after migration.
Analyze the time complexity of this TypeScript function that processes an array of numbers.
function sumPositiveNumbers(nums: number[]): number {
let sum = 0;
for (const num of nums) {
if (num > 0) {
sum += num;
}
}
return sum;
}
This function adds up all positive numbers in the input array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop that goes through each number in the array once.
- How many times: Exactly once for each element in the input array.
As the input array gets bigger, the function checks each number once, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and additions |
| 100 | About 100 checks and additions |
| 1000 | About 1000 checks and additions |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time it takes grows in a straight line with the number of items.
[X] Wrong: "Adding TypeScript types makes the code run slower because of extra checks at runtime."
[OK] Correct: TypeScript checks happen only during development and do not add runtime overhead, so the running time depends on the code logic, not the types.
Understanding how adding types affects your code helps you write clear, maintainable programs without worrying about slowing them down.
"What if we changed the function to check pairs of numbers instead of single numbers? How would the time complexity change?"