Solution: Cache Expensive Function Calls via Proxy
Explore how to implement caching for costly function calls in Node.js using the Proxy pattern. Learn to intercept function calls with the apply trap, store results based on input arguments, and return cached outputs to improve performance without modifying the original function.
We'll cover the following...
Solution explanation
Lines 2–5: We define
heavyComputation()to simulate a costly calculation.It logs
"Computing..."each time it runs, signaling real work.The random component ensures that identical inputs normally produce different results, making caching effects visible.
Lines 8–25: The
createCachedFunction()builds a Proxy that intercepts calls to the given function.A
cachemap stores previous results keyed by the serialized arguments.This ensures unique combinations of inputs map to specific cached outputs.
Lines 12–21: The
apply()trap handles any direct or indirect function invocation.