Make Object Immutable
Freeze an object all the way down, because Object.freeze only handles the top level.
JavaScript · ES6 — Pratik Rai ·
Copy a nested structure so nothing is shared — including the cases that break a naive recursion.
Write deepClone(value) returning a copy that shares no references with the input.
Handle plain objects and arrays, keep Date, Map and Set intact rather than flattening them, and do not hang on a structure that contains itself.
Input:
JSfile.javascript1const original = { list: [1, { deep: true }] }; 2const copy = deepClone(original); 3copy.list[1] === original.list[1];
Output:
false
The nested object was copied, not referenced.
JSON.parse(JSON.stringify(x)) is the one-liner everyone reaches for; it loses Dates, Maps, Sets and undefined, and throws on a cycle.structuredClone handles all of the above natively — and still throws on functions.Goal: Produce a copy that shares nothing with the original, cycles included.
Continue learning with these related challenges
Freeze an object all the way down, because Object.freeze only handles the top level.
JavaScript · ES6 — Pratik Rai ·
Compare two values structurally, because === only ever compares references.
JavaScript · ES6 — Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6 — Pratik Rai ·
Freeze an object all the way down, because Object.freeze only handles the top level.
JavaScript · ES6
Pratik Rai ·
Compare two values structurally, because === only ever compares references.
JavaScript · ES6
Pratik Rai ·
Group an array into buckets by a key function — now a real language feature as Object.groupBy.
JavaScript · ES6
Pratik Rai ·