Generic factory pattern in Typescript - Time & Space Complexity
We want to see how the time cost changes when using a generic factory pattern in TypeScript.
How does creating objects with this pattern scale as we ask for more objects?
Analyze the time complexity of the following code snippet.
interface Product {
name: string;
}
function createProduct(ctor: new () => T): T {
return new ctor();
}
class Toy implements Product {
name = 'Toy';
}
const toy = createProduct(Toy);
This code defines a generic factory function that creates an object of any class that implements Product.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a single object instance using the constructor.
- How many times: Exactly once per call to the factory function.
Each time we call the factory, one new object is created. If we call it multiple times, the work grows directly with the number of calls.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The time grows linearly as we create more objects.
Time Complexity: O(n)
This means the time to create n objects grows directly in proportion to n.
[X] Wrong: "Creating an object with the factory is instant and does not depend on how many times we call it."
[OK] Correct: Each call creates a new object, so more calls mean more work, not zero time.
Understanding how object creation scales helps you explain performance in real apps and shows you know how patterns affect speed.
"What if the factory function created multiple objects inside a loop? How would the time complexity change?"