MediumTypeScript

Proxy

TypeScriptDesign PatternsStructuralProxy

Put a stand-in object in front of a real, possibly-expensive object to control access to it — here, a caching proxy that avoids re-fetching the same id twice.

Implement `CachingProxy.fetchData(id)`: return the cached result if seen before, otherwise delegate to the wrapped RealDataService (which tracks how many times it was actually called) and cache the result.

solve(ids) fetches every id through the proxy and returns { results, realCallCount }.

solve(['a', 'a', 'b']){ results: ['data-a', 'data-a', 'data-b'], realCallCount: 2 } — the real service was only hit twice.

Sample tests

Test #1Repeated id is cached
Input: [["a","a","b"]]
Output: {"results":["data-a","data-a","data-b"],"realCallCount":2}
Test #2No ids
Input: [[]]
Output: {"results":[],"realCallCount":0}
Test #3Interleaved repeats still cache correctly
Input: [["x","y","x","x"]]
Output: {"results":["data-x","data-y","data-x","data-x"],"realCallCount":2}