Skip to the solution
EasyDSAAsked in 20248 min read

Implement an Immutable setIn(obj, path, value) That Never Mutates the Original

818 views

The problem

Problem, as an interviewer would state it: "Implement setIn(obj, path, value) — setting a deeply nested value at path and returning a genuinely NEW object, while leaving the original COMPLETELY untouched, and correctly SHARING (not copying) any sibling data that was not actually on the changed path — matching the real, well-known Immutable.js setIn convention."

Examples:

Code
const original = { user: { name: "Ada", address: { city: "London" } } };
setIn(original, "user.address.city", "Paris");
// { user: { name: "Ada", address: { city: "Paris" } } }
// original is completely unchanged

Clarifying questions expected:

  • Should every object ALONG the changed path be a genuinely new reference, while sibling data NOT on that path is structurally SHARED (same reference) rather than deep-copied?
  • Does this need to correctly CREATE intermediate objects if the path does not fully exist yet in the original?
  • Should the path be accepted as a dot-separated string, an array of keys, or both?

Code / implementation expected: Yes — real, direct proof the original is completely untouched, that every object along the changed path is a new reference while unrelated sibling data is structurally shared, and that missing intermediate path segments are correctly created.

  • 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

8 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: setIn() leaves the original completely untouched, creates new references only along the changed path, and structurally shares unrelated sibling data

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 28 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

Implement Array.prototype.flat() — flatten with depth

Continue