Skip to content

fix(clone): support circular references - #105

Merged
ASafaeirad merged 1 commit into
fullstacksjs:mainfrom
CyberneticX-Tech:fix/clone-circular-references
Sep 10, 2026
Merged

fix(clone): support circular references#105
ASafaeirad merged 1 commit into
fullstacksjs:mainfrom
CyberneticX-Tech:fix/clone-circular-references

Conversation

@CyberneticX-Tech

Copy link
Copy Markdown
Contributor

Closes #104

Problem

clone recurses unconditionally, so a value that references itself overflows the call stack:

const obj: any = {};
obj.self = obj;
clone(obj); // RangeError: Maximum call stack size exceeded

const arr: any[] = [];
arr[0] = arr;
clone(arr); // RangeError: Maximum call stack size exceeded

Fix

Track visited values in a WeakMap and register each container in it before cloning its children, so a cycle resolves to the clone already in progress. A value that appears more than once is now cloned once and shared by every reference in the output, which matches structuredClone semantics.

cloneMap previously round-tripped through Object.fromEntries/Object.entries, which coerced non-string keys to strings. It now iterates the map directly, so new Map([[{ id: 1 }, 'foo']]) keeps its object key.

The WeakMap is created per top-level clone call, so nothing is retained between calls.

Tests

Added regression coverage for self-referencing objects, arrays, maps and sets, a mutually referencing pair, shared-reference identity, and non-string map keys.

Full suite passes (616 tests), plus type-check, eslint and build.

clone recursed unconditionally, so a value referencing itself overflowed the
call stack. Track visited values in a WeakMap and register each container
before cloning its children, so a cycle resolves to the clone in progress and
a repeated reference is cloned once and shared.

cloneMap no longer round-trips through Object.fromEntries, which coerced
non-string keys to strings.
Comment thread src/object/clone.ts
@ASafaeirad
ASafaeirad merged commit e77d229 into fullstacksjs:main Sep 10, 2026
2 checks passed
@github-actions

Copy link
Copy Markdown

馃帀 This PR is included in version 4.24.1 馃帀

The release is available on:

Your semantic-release bot 馃摝馃殌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: clone function fails on circular object references

3 participants