Tech Interview RoomStudy guides

Frontend Coding

Implement deep clone and deep equal, handling Dates, Maps, Sets and circular references.

Intermediate · 2 min read · Lesson 5 of 10 in Frontend Coding

deepClone

  • Primitives and functions are returned as they are.
  • Date, RegExp, Map and Set need special handling.
  • Arrays and plain objects are copied key by key, recursively.
  • A WeakMap from original to copy handles circular references and shared references (the same object referenced twice stays one object in the copy).
  • Preserve the prototype with Object.create(Object.getPrototypeOf(obj)) if class instances matter.

deepEqual

  • Same reference or Object.is equal → true.
  • Different types or constructors → false.
  • Compare Dates by time, RegExps by source and flags, Maps and Sets by entries, objects by own keys (same count, each value deep equal).
  • Track visited pairs to stop infinite recursion on cycles.

In production, structuredClone (built in) and lodash.isEqual cover most needs; interviewers ask for these to test recursion and edge-case thinking.

js
function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== 'object') return value;   // primitives and functions
  if (seen.has(value)) return seen.get(value);                     // cycles and shared refs

  if (value instanceof Date) return new Date(value.getTime());
  if (value instanceof RegExp) return new RegExp(value.source, value.flags);
  if (value instanceof Map) {
    const copy = new Map();
    seen.set(value, copy);
    value.forEach((v, k) => copy.set(deepClone(k, seen), deepClone(v, seen)));
    return copy;
  }
  if (value instanceof Set) {
    const copy = new Set();
    seen.set(value, copy);
    value.forEach(v => copy.add(deepClone(v, seen)));
    return copy;
  }
  const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
  seen.set(value, copy);
  for (const key of Reflect.ownKeys(value)) copy[key] = deepClone(value[key], seen);
  return copy;
}

function deepEqual(a, b, seen = new Map()) {
  if (Object.is(a, b)) return true;
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
  if (a.constructor !== b.constructor) return false;
  if (seen.get(a) === b) return true;                                // already comparing this pair
  seen.set(a, b);

  if (a instanceof Date) return a.getTime() === b.getTime();
  if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;
  if (a instanceof Map) {
    if (a.size !== b.size) return false;
    for (const [k, v] of a) if (!b.has(k) || !deepEqual(v, b.get(k), seen)) return false;
    return true;
  }
  if (a instanceof Set) {
    if (a.size !== b.size) return false;
    for (const v of a) if (!b.has(v)) return false;
    return true;
  }
  const keysA = Reflect.ownKeys(a);
  const keysB = Reflect.ownKeys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every(k => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k], seen));
}

// Demo
const original = { name: 'cart', created: new Date(0), tags: new Set(['a']), prices: new Map([['x', 10]]), items: [{ id: 1 }] };
original.self = original;                                            // circular

const copy = deepClone(original);
assert.notEqual(copy, original);
assert.equal(copy.self, copy);                                       // cycle preserved in the copy
assert.notEqual(copy.items[0], original.items[0]);                  // nested objects are new
assert.ok(copy.created instanceof Date && copy.created !== original.created);
assert.ok(deepEqual(copy, original));

copy.items[0].id = 2;
assert.ok(!deepEqual(copy, original));
assert.ok(deepEqual([1, { a: NaN }], [1, { a: NaN }]));
assert.ok(!deepEqual({ a: 1 }, { a: 1, b: undefined }));
console.log('deepClone and deepEqual handle dates, maps, sets and cycles');

Example

A shallow equality check is what React's memo and many selectors use; it is the "one level" version of the same idea:

js
function shallowEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;
  const ka = Object.keys(a), kb = Object.keys(b);
  return ka.length === kb.length && ka.every(k => Object.hasOwn(b, k) && Object.is(a[k], b[k]));
}
assert.ok(shallowEqual({ id: 1, tag: 'x' }, { id: 1, tag: 'x' }));
assert.ok(!shallowEqual({ list: [1] }, { list: [1] }));   // different array references

Follow-up questions interviewers ask

Try answering each one before you open it.

Why does the Set comparison above use has() instead of deep comparison?

Set.has uses SameValueZero, so two different objects with the same contents are not found. Deep comparison of Sets of objects needs a matching step (for each item in a, find an unused deep-equal item in b), which is O(n²). Mention the trade-off; most interviewers accept the simpler version for primitives.