Type alias for functions in Typescript - Time & Space Complexity
We want to see how the time it takes to run code changes when we use type aliases for functions in TypeScript.
Specifically, how does the program's work grow as the input size grows?
Analyze the time complexity of the following code snippet.
type StringModifier = (input: string) => string;
function applyModifiers(input: string, modifiers: StringModifier[]): string {
let result = input;
for (const modify of modifiers) {
result = modify(result);
}
return result;
}
This code applies a list of string-changing functions one after another to an input string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of functions (modifiers).
- How many times: Once for each function in the modifiers array.
Each added function means one more step to apply to the string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: The work grows directly with the number of functions to apply.
Time Complexity: O(n)
This means the time to finish grows in a straight line as you add more functions to apply.
[X] Wrong: "Using a type alias for functions makes the code slower because it adds extra steps."
[OK] Correct: The type alias only helps with naming and checking types; it does not add any extra work when running the code.
Understanding how loops over function lists affect time helps you explain how your code scales and shows you can think about performance clearly.
"What if each function in the modifiers array also loops over the string characters? How would the time complexity change?"