0
0
Typescriptprogramming~5 mins

Generic repository pattern in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic repository pattern
O(n)
Understanding Time Complexity

We want to understand how the time needed to run a generic repository grows as the amount of data changes.

Specifically, how do the repository's methods behave when handling more items?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class GenericRepository<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  find(predicate: (item: T) => boolean): T | undefined {
    return this.items.find(predicate);
  }
}
    

This code defines a generic repository that stores items and can add new ones or find an item by a condition.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The find method loops through the items array to check each item against the condition.
  • How many times: It may check up to all items in the array in the worst case.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows directly with the number of items. More items mean more work.

Final Time Complexity

Time Complexity: O(n)

This means the time to find an item grows linearly as the number of stored items increases.

Common Mistake

[X] Wrong: "Finding an item is always fast and takes the same time no matter how many items there are."

[OK] Correct: The find method may need to check many items one by one, so more items usually mean more time.

Interview Connect

Understanding how generic repositories work and their time costs helps you explain data handling clearly and confidently in real projects.

Self-Check

"What if the repository stored items in a map keyed by an ID? How would the time complexity of finding an item change?"