Question 53
Question
How would you create an interdependent object graph using WeakMap
and WeakSet
?
Answer
Here's how you can build an interdependent object graph leveraging the strengths of WeakMap
and WeakSet
:
Core Concepts:
Object Relationships: We'll define relationships between objects (e.g., "owns," "references") using
WeakMap
to store these connections.Weak References for Safety: Employ
WeakMap
andWeakSet
throughout to ensure that if an object is no longer referenced elsewhere, it gets garbage collected without causing circular dependencies or memory leaks.
Example: Representing a Simple Social Network
Explanation:
Person
Class: EachPerson
object has:A
name
.A private
_relationships
WeakMap
to store its connections (friendships).
addFriend()
Method:Sets a 'friendsWith' relationship from one person (
this
) to the friend using_relationships.set()
.Does the same for the reverse direction ('knows') on the friend object, establishing a bidirectional connection.
Weak References: The use of
WeakMap
ensures that:If a
Person
object is no longer referenced by anything else (e.g., removed from memory), its_relationships
will automatically be cleared, breaking the connection and allowing for garbage collection.
Additional Considerations:
Traversing Relationships: You can iterate through relationships using
for...of
loops or manually checking_relationships
for keys like 'friendsWith'.Complex Graphs: For more intricate graphs with various relationship types, consider using a custom class to represent connections (e.g.,
Relationship
with properties for type and objects).
Last updated