22.4. Remove circular references
Topics
This question is in
22. SerializationAn 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
function decycle(value, marker) // returns a copy of valuevalue: any value.marker(optional): the value that replaces a circular reference. When it is missing, it is the string"[Circular]". Any other value,nullincluded, is used as it is.
Requirements
- Primitives are returned as they are.
- Objects and arrays are copied at every level: no object or array of the result is one of the input's. Arrays stay arrays.
- 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. - 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.
- The given
markeris used as it is, not copied. - The input is not changed.
- The result has no cycle, so
JSON.stringifycan write it whenever the rest is something JSON can hold.decycleremoves cycles only; it does not convert other values. A BigInt is a primitive and is kept (rule 1), soJSON.stringifystill throws aTypeErrorfor 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 ornull. - A
Dateis copied as a newDatewith the same time. - Any other object is copied as a plain object with only its own enumerable string keys (as
Object.keysgives them). Every key is copied as an own property of the copy,__proto__included. - A chain thousands of levels deep works, and each call starts fresh.
Examples
const node = { name: "a" };
node.self = node;
decycle(node); // { name: "a", self: "[Circular]" }
decycle(node, null); // { name: "a", self: null }const user = { name: "ada", friends: [] };
user.friends.push({ name: "bob", friends: [user] });
JSON.stringify(decycle(user));
// '{"name":"ada","friends":[{"name":"bob","friends":["[Circular]"]}]}'const shared = { v: 1 };
decycle({ a: shared, b: shared }); // { a: { v: 1 }, b: { v: 1 } }: not circularEnvironment
- Plain JavaScript in a browser page; the tests call the global
decyclefromdecycle.js. structuredClonekeeps cycles, so it does not help here.Map,Setand typed arrays are out of scope.
Hints
- Which objects count as "still inside of", and when does an object stop counting?
- 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