22.3. Detect a circular reference
Topics
This question is in
22. SerializationJSON.stringify throws "Converting circular structure to JSON" and stops there: it does not say where the loop is. In a big state tree, a parent link or an event target stored in the wrong place is hard to find by hand. A function that returns the path to the property that closes the loop turns that error into a one-line fix.
Write findCycle(value) in find-cycle.js. It walks value depth first and returns the keys from value to the first property that points back to an object or array the walk is still inside. When there is no such property, it returns null.
Signature
function findCycle(value) // returns an array of strings, or nullvalue: any value.- Returns the path as an array of keys, in the order they are followed. The last key is the property that points back.
Requirements
- Primitives (
nullandundefinedincluded) have no cycle:null. - Flat and nested values with no loop return
null. - A property pointing to the object it is on, to any object around it, or to the root returns the path to that property.
- Arrays are walked like objects. Every key in the path is a string, as
Object.keysgives it ("0","1"…). - A shared object (the same object reached twice side by side, or a diamond) is not a cycle. The walk keeps going past it.
- Keys are walked in
Object.keysorder, depth first, and the first cycle found is returned. - Only own enumerable string keys are followed: symbol keys, non-enumerable and inherited properties are ignored.
- The value is not changed, and every call starts fresh.
- A chain thousands of levels deep works.
- An object that is reached many times is walked once: a value made of 25 objects that each point to the next one twice must finish in well under a second.
Examples
const node = { name: "a" };
node.self = node;
findCycle(node); // ["self"]const team = { name: "team", members: [{ name: "ada" }, { name: "bob" }] };
team.members[1].team = team;
findCycle(team); // ["members", "1", "team"]const shared = { v: 1 };
findCycle({ a: shared, b: shared }); // null: shared, but no loop
findCycle(42); // nullEnvironment
- Plain JavaScript in a browser page; the tests call the global
findCyclefromfind-cycle.js. - Functions are values, not containers: their properties are not walked. Entries of
MapandSetare out of scope. JSON.stringifycannot help here: it only says that a cycle exists.
Hints
- A shared object and a loop both reach the same object twice. What is different about the second time in a loop?
- When you have finished walking an object and found nothing, can anything below it ever lead back up?
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