Skip to curriculum
Jump to the editor

22.4. Remove circular references

Medium
Topics

This question is in

22. Serialization
15–30 min

An error reporter wants to send the state of the page along with a crash. The state holds a tree whose nodes point to their parents, and JSON.stringify throws on the first loop, so the report is lost together with the crash. Logging libraries solve this by copying the value first and replacing each reference that loops back with a marker such as "[Circular]".

Write decycle(value, marker) in decycle.js. It returns a deep copy of value in which every property that points to an object or array the copy is still inside of is replaced by marker. The result never contains a cycle of its own, which is the one thing that stops JSON.stringify from writing an otherwise ordinary state tree.

Signature

JAVASCRIPT
function decycle(value, marker) // returns a copy of value
  • value: any value.
  • marker (optional): the value that replaces a circular reference. When it is missing, it is the string "[Circular]". Any other value, null included, is used as it is.

Requirements

  1. Primitives are returned as they are.
  2. Objects and arrays are copied at every level: no object or array of the result is one of the input's. Arrays stay arrays.
  3. A reference to the object itself, to any object around it, or to the root, is replaced by marker. This includes arrays that hold themselves.
  4. A shared object (reached again after the copy has left it) is not circular: it is copied in every place it appears. A cycle after a shared object is still found.
  5. The given marker is used as it is, not copied.
  6. The input is not changed.
  7. The result has no cycle, so JSON.stringify can write it whenever the rest is something JSON can hold. decycle removes cycles only; it does not convert other values. A BigInt is a primitive and is kept (rule 1), so JSON.stringify still throws a TypeError for it, and a marker is placed as it is (rule 5), so an object marker that contains a cycle brings a cycle back. Use a marker JSON can write, such as a string or null.
  8. A Date is copied as a new Date with the same time.
  9. Any other object is copied as a plain object with only its own enumerable string keys (as Object.keys gives them). Every key is copied as an own property of the copy, __proto__ included.
  10. A chain thousands of levels deep works, and each call starts fresh.

Examples

JAVASCRIPT
const node = { name: "a" };
node.self = node;
decycle(node);         // { name: "a", self: "[Circular]" }
decycle(node, null);   // { name: "a", self: null }
JAVASCRIPT
const user = { name: "ada", friends: [] };
user.friends.push({ name: "bob", friends: [user] });
JSON.stringify(decycle(user));
// '{"name":"ada","friends":[{"name":"bob","friends":["[Circular]"]}]}'
JAVASCRIPT
const shared = { v: 1 };
decycle({ a: shared, b: shared });   // { a: { v: 1 }, b: { v: 1 } }: not circular

Environment

  • Plain JavaScript in a browser page; the tests call the global decycle from decycle.js.
  • structuredClone keeps cycles, so it does not help here. Map, Set and typed arrays are out of scope.

Hints

  1. Which objects count as "still inside of", and when does an object stop counting?
  2. Where should the marker be written so that the input keeps its own references?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…