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
WeakMapto store these connections.Weak References for Safety: Employ
WeakMapandWeakSetthroughout 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
class Person {
constructor(name) {
this.name = name;
this._relationships = new WeakMap(); // Store relationships (e.g., 'friendsWith')
}
addFriend(friend) {
this._relationships.set('friendsWith', friend);
friend._relationships.set('knows', this);
}
}
const john = new Person('John');
const jane = new Person('Jane');
john.addFriend(jane);
// Now, 'john' and 'jane' have a relationship via their _relationships WeakMaps.Explanation:
PersonClass: EachPersonobject has:A
name.A private
_relationshipsWeakMapto 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
WeakMapensures that:If a
Personobject is no longer referenced by anything else (e.g., removed from memory), its_relationshipswill automatically be cleared, breaking the connection and allowing for garbage collection.
Additional Considerations:
Traversing Relationships: You can iterate through relationships using
for...ofloops or manually checking_relationshipsfor keys like 'friendsWith'.Complex Graphs: For more intricate graphs with various relationship types, consider using a custom class to represent connections (e.g.,
Relationshipwith properties for type and objects).
Last updated