🔄 Removing Circular References from Objects
Category: js / utils
Difficulty: hard
Circular references can create serious problems in JavaScript — from infinite recursions to JSON.stringify errors. Here’s how to remove cycles both structurally and during serialization using idiomatic, memory-safe JavaScript. 🔁 1. Structural Removal with WeakSet Purpose: Remove circular references in-place from object graphs (e.g., linked lists, trees, graphs). How It Works: A recursive traversal tracks visited objects using a WeakSet. If a reference is encountered again, it is removed. Code: [code example] Test Case: [code example] 🧵 2. Serialization-Safe: JSON.stringify() with Replacer Purpose: Remove cycles on-the-fly during serialization to JSON. Useful when you don't want to mutate the original object. How It Works: JSON.stringify accepts a replacer function. You can use a WeakSet inside this replacer to track seen objects and return undefined for repeats (i.e., remove cycles). Code: [code example] Usage: [code example]...