I found this code snippet in a file, core/index.ts. Why not use a proper Set? why would react-scan author decide to use WeakSet? To draw some conclusion around that, we first need to understand difference between WeakSet and Set in JavaScript.
A WeakSet is a collection of garbage-collectable values, including objects and non-registered symbols. A value in the WeakSet may only occur once. It is unique in the WeakSet's collection.
Values of WeakSets must be garbage-collectable. Most primitive data types can be arbitrarily created and don’t have a lifetime, so they cannot be stored. Objects and non-registered symbols can be stored because they are garbage-collectable.
WeakSets are collections of objects and symbols only. They cannot contain arbitrary values of any type, as Sets can.
The WeakSet is weak, meaning references to objects in a WeakSet are held weakly. If no other references to a value stored in the WeakSet exist, those values can be garbage collected.
Now it makes sense why typeof node === ‘object’ check is in place. Can you guess why? this is because only Object and Symbols can be stored in the WeakMap that are garbage collectable if they are not referenced elsewhere.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.