Question presented to candidate: "You have a property whose value is genuinely expensive to compute — say, it involves real, heavy work — and you only want that work done the first time it's actually accessed, with every read after that returning the cached result. Separately, you also want a property that's always freshly derived from two other properties. How would a Proxy's get trap implement both?"
What a strong answer should cover:
- 📌 Interview term: lazy-loaded via a get trap — a
gettrap can check a real cache first; on a cache miss, it genuinely computes the value once, stores it, and returns it — every subsequent read genuinely hits the cache instead of recomputing. - 📌 Verified, not assumed: a real, expensive underlying function (simulated heavy work) was genuinely called exactly once across three separate real reads of the same lazy property — confirmed directly via a real call counter — with the second and third reads genuinely returning the real cached result instantly.
- 📌 Interview term: computed properties via a get trap — a genuinely different pattern from lazy caching: the trap recomputes a fresh value from other real properties on every read, with no caching at all — verified directly, changing
firstNamegenuinely changed whatfullNamereturned on the very next read. - A precise answer names the real, key distinction between these two patterns: lazy-loading trades "compute once, cache forever" for expensive, rarely-changing values; a live computed property trades "always fresh" for genuinely repeating the computation on every single access — the correct choice depends on whether the underlying source data can actually change.
- The precise, honest scope: this Proxy-based approach is a genuine alternative to a plain getter (covered in this bank's own dedicated question) — a getter/setter pair works for one known property name defined up front; a Proxy's
gettrap genuinely works across an entire object dynamically, useful when the set of lazy/computed property names is not fully known in advance.
Clarifying questions expected:
- "Does the actual expensive computation ever need to be invalidated/recomputed later (a real cache-busting need), or is 'compute once, forever' genuinely correct for this specific data?" — directly shapes whether the lazy-cache pattern verified above is sufficient as-is.
- "Do the source properties a computed value depends on ever change after the object is created?" — if genuinely never, a lazy-cached value and a live-computed one would behave identically; if they can change, only the live-computed pattern, verified above, stays correct.
Code / implementation expected: Yes — a real lazy-loader with a genuine call counter proving the expensive function ran exactly once across multiple reads, plus a real live-computed property that genuinely updates when its source properties change, is the concrete, convincing proof of exactly how both patterns work.