Attaching Metadata Without Owning Players

The replay history is bounded now, so a match that leaves it has no owner left in the processor. The anti-cheat team wants a review note on each player the processor scores, such as whether their rounds were checked. But the player objects belong to the lobby service, which creates them and lets them go when a player logs off.

The first draft stored the notes in a Map keyed by a player object. That Map is one more strong owner, so every player who logged on today stays reachable. In this lesson, you’ll attach notes to players without owning them, and you’ll find out what a weak map still holds on to.

Key Notes by Player With a WeakMap

A Python processor faces the same choice. A dict keyed by Player instances owns them, so you use weakref.WeakKeyDictionary, whose references to its keys don’t keep them alive:

Language: Python
import weakref

class Player:
    def __init__(self, id, team):
        self.id = id
        self.team = team

review_notes = weakref.WeakKeyDictionary()
player = Player("P1", "Falcons")
review_notes[player] = {"checked": True}
print(player in review_notes, review_notes[player])

Python finds the note through the player object:

Language: Program Output
True {'checked': True}

JavaScript’s version is a WeakMap. You create one with new, as you would a Map, and its .set(), .get(), and .has() methods behave like the Map methods of the same names:

Language: JavaScript
const reviewNotes = new WeakMap();
const player = { id: "P1", team: "Falcons" };

reviewNotes.set(player, { checked: true });
console.log(reviewNotes.has(player), reviewNotes.get(player));
console.log(reviewNotes.get({ id: "P1", team: "Falcons" }));

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.