Skip to the solution
MediumLow-Level DesignAsked in 20247 min read

Implement a WeakMap-Like API Shape (and Why True Weak References Cannot Be Polyfilled)

2.6k views

The problem

Problem, as an interviewer would state it: "Implement an object exposing the same API SHAPE as a real WeakMap (get/set/has/delete) — then explain, honestly, why it can NEVER actually replicate WeakMap's real, defining behavior: automatic garbage collection of unreferenced keys."

Examples:

Code
const wm = new FakeWeakMap();
wm.set(someObject, "data");
// the API works identically -- but the polyfill can NEVER let someObject be garbage collected

Clarifying questions expected:

  • Should the polyfill genuinely try to replicate weak references, or is matching the API SHAPE while being honest about the limitation the actual goal?
  • Should it reject non-object keys, matching real WeakMap's own documented contract?
  • Is there ANY real JS-level way to observe or influence garbage collection directly?

Code / implementation expected: Yes — real, direct proof that the API shape works correctly, PLUS a real, honest demonstration of the actual memory-leak limitation: the polyfill's internal storage is proven to retain a reference even after every other reference to a key is dropped.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the polyfill's API shape works correctly, but its internal storage genuinely never shrinks after the only external key reference is dropped

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 63 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

JSON schema validator

Continue