0
0
Typescriptprogramming~5 mins

Generic arrow functions in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic arrow functions
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The map method loops over each item in the input array.
  • How many times: It runs once for every element in the array.
How Execution Grows With Input

As the input array gets bigger, the function does more work by visiting each item once.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding how generic arrow functions behave helps you explain your code clearly and shows you know how input size affects performance.

Self-Check

What if the function used nested loops inside the map? How would the time complexity change?