...

/

Solution: Cache Expensive Function Calls via Proxy

Solution: Cache Expensive Function Calls via Proxy

Use the apply trap to cache results of function calls based on arguments.

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.

    • cache map 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.

...