0
0
Typescriptprogramming~5 mins

Generic factory pattern in Typescript - Time & Space Complexity

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

Scenario Under Consideration

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

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.
How Execution Grows With Input

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
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: The time grows linearly as we create more objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to create n objects grows directly in proportion to n.

Common Mistake

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

Interview Connect

Understanding how object creation scales helps you explain performance in real apps and shows you know how patterns affect speed.

Self-Check

"What if the factory function created multiple objects inside a loop? How would the time complexity change?"