Generic arrow functions in Typescript - Time & Space Complexity
We want to understand how the time it takes to run a generic arrow function changes as the input size grows.
Specifically, how does the function's work increase when given more data?
Analyze the time complexity of the following code snippet.
const identity = <T> (items: T[]): T[] => {
return items.map(item => item);
};
const numbers = [1, 2, 3, 4, 5];
const result = identity(numbers);
This code defines a generic arrow function that returns a new array by copying each item from the input array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
mapmethod loops over each item in the input array. - How many times: It runs once for every element in the array.
As the input array gets bigger, the function does more work by visiting each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Generic arrow functions always add extra hidden work and slow down the code a lot."
[OK] Correct: The generic part only helps with types and does not add extra loops or slow down the function itself.
Understanding how generic arrow functions behave helps you explain your code clearly and shows you know how input size affects performance.
What if the function used nested loops inside the map? How would the time complexity change?