Learning on Web Dev Open is free for all.

Interview Prep · CodeDeep clone a value
← Code

Deep clone a value

Medium25 minFree, no account

Six lines get you 80%. The cycle and the Date get you the other 20%.


The question

Write deepClone(value) that handles nested objects and arrays, Date, Map, Set, and circular references.

The clone must share no mutable structure with the original.

const a = { d: new Date(), s: new Set([1, 2]), list: [1, [2, 3]] };
a.self = a;

const b = deepClone(a);
b.self === b          // true, the cycle is preserved, not followed
b.d instanceof Date   // true, not a string
b.list[1] !== a.list[1]
25:00Commit to an answer before you open the solution. Reading it first teaches you to recognise good answers, which is not the skill being tested.

Stuck?

0 of 3 hints taken

The worked solution

written by a person · not a grade

Score yourself

0 of 5 marked
  • Rejected the JSON approach with specific reasons15
  • Correct recursion over objects and arrays25
  • Cycles handled with a WeakMap registered before recursing30
  • Date, Map and Set handled as themselves20
  • Stated complexity and the recursion-depth limit10

We run no AI here and nothing on this page grades you. The score is yours, and the useful number is the one you get on the same problem a month from now, cold.

kept in this browser only