Search⌘ K
AI Features

Solution: Add Caching Without Touching Core Logic

Discover how to use the Decorator Pattern to transparently extend functions with caching in Node.js. Learn to create a reusable withCache decorator that stores results, reduces latency, logs cache activity, and works seamlessly with both synchronous and asynchronous calls while preserving original function behavior.

Solution explanation

  • Lines 2–7: We define getProductDetails, a simulated async API call. It logs every fetch and resolves after 150 ms, representing a costly service operation.

  • Lines 10–26: We create withCache(fn), a stateful decorator:

    • We initialize a Map named cache to store results.

    • Inside the returned async wrapper, we compute a cache key by serializing the arguments with JSON.stringify.

    • If the ...