Skip to the solution
EasyLow-Level DesignAsked in 20249 min read

Immer-like draft proxies

1.6k views

The problem

Problem, as an interviewer would state it: "Implement a simplified produce(base, recipe) — like Immer — letting the recipe mutate a 'draft' object naturally, while producing a genuinely NEW immutable result with STRUCTURAL SHARING: unchanged nested parts of the object must be the EXACT SAME reference as the original, not just equal-looking copies."

Examples:

Code
const result = produce(base, draft => { draft.count = 2; });
result.user === base.user; // true -- untouched, structurally shared
result.count === 2 && base.count === 1; // true -- original unmutated

Clarifying questions expected:

  • Does "structural sharing" specifically mean REFERENCE equality for untouched parts, not just deep equality?
  • If a deeply nested field changes, do all its ANCESTOR objects on the path to it also need new references?
  • Should this handle arrays the same way as plain objects?

Code / implementation expected: Yes — real, direct proof that an untouched nested field returns the EXACT SAME reference as the original, while a genuinely modified field (and its ancestors) get new references — this was caught failing on a first attempt and fixed.

  • 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

9 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: produce() achieves genuine structural sharing — untouched fields, siblings, and nested branches all return the exact same reference

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 15 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 nextEasy

Graph bfs traversal

Continue