Deep Clone With Cycle Detection

A structural deep clone that handles cycles and shared references without infinite recursion, preserving Maps, Sets, Dates and typed arrays.

JavascriptData Fetching

Code

export function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== "object") return value;
  if (seen.has(value)) return seen.get(value);

  if (Array.isArray(value)) {
    const copy = [];
    seen.set(value, copy);
    for (const item of value) copy.push(deepClone(item, seen));
    return copy;
  }
  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);
    for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen));
    return copy;
  }
  if (value instanceof Set) {
    const copy = new Set();
    seen.set(value, copy);
    for (const v of value) copy.add(deepClone(v, seen));
    return copy;
  }
  if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
    return value.slice();
  }
  if (value instanceof ArrayBuffer) return value.slice(0);

  const copy = {};
  seen.set(value, copy);
  for (const [k, v] of Object.entries(value)) copy[k] = deepClone(v, seen);
  return copy;
}