Generic repository pattern in Typescript - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
findmethod loops through theitemsarray to check each item against the condition. - How many times: It may check up to all items in the array in the worst case.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the number of items. More items mean more work.
Time Complexity: O(n)
This means the time to find an item grows linearly as the number of stored items increases.
[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.
Understanding how generic repositories work and their time costs helps you explain data handling clearly and confidently in real projects.
"What if the repository stored items in a map keyed by an ID? How would the time complexity of finding an item change?"