...
/Solution: Add Caching Without Touching Core Logic
Solution: Add Caching Without Touching Core Logic
Use a stateful decorator to add caching (memoization) around an async function, improving performance without changing its logic.
We'll cover the following...
We'll cover the following...
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
Mapnamedcacheto store results.Inside the returned async wrapper, we compute a cache key by serializing the arguments with
JSON.stringify.If the ...