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;
}

A naive recursive clone blows the stack on cyclic structures, and JSON round trips silently drop Dates, Maps and undefined.

Use case: engineers copying state trees that may contain cycles or shared nodes

Inputs / outputs

  • Input: any value including objects, arrays, Map, Set, Date, typed arrays, cycles
  • Output: a structurally equal copy with shared references preserved

Error conditions

  • unsupported value types (functions, symbols) are passed through by reference

Approach

maintain a WeakMap of already-cloned nodes so cycles and shared subtrees map back to the same clone; dispatch on type for the structured containers.

Implementation

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;
}

Verification tests

import { test } from "node:test";
import assert from "node:assert/strict";
import { deepClone } from "./example.mjs";

test("clones nested structures", () => {
  const source = { a: { b: [1, 2, { c: "x" }] }, d: new Date(0) };
  const copy = deepClone(source);
  assert.deepEqual(copy, source);
  assert.notEqual(copy.a, source.a);
  assert.notEqual(copy.a.b, source.a.b);
  assert.notEqual(copy.d, source.d);
});

test("preserves cycles without infinite recursion", () => {
  const node = { name: "root" };
  node.self = node;
  const copy = deepClone(node);
  assert.equal(copy.name, "root");
  assert.equal(copy.self, copy);
});

test("keeps shared references identical", () => {
  const shared = { id: 1 };
  const source = { left: shared, right: shared };
  const copy = deepClone(source);
  assert.equal(copy.left, copy.right);
  assert.notEqual(copy.left, shared);
});

test("supports Map Set and typed arrays", () => {
  const source = { m: new Map([["k", 1]]), s: new Set([1, 2]), t: new Uint8Array([1, 2, 3]) };
  const copy = deepClone(source);
  assert.deepEqual(copy.m, source.m);
  assert.deepEqual(copy.s, source.s);
  assert.deepEqual([...copy.t], [1, 2, 3]);
  assert.notEqual(copy.t, source.t);
});

Dependencies and running

No external dependencies (standard library only).

Runtime: node >= 18 Entry point: node example.mjs

Limitations and error handling

functions and symbols are copied by reference; class prototypes are not preserved (plain objects).

Verification boundary

execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox