Skip to content

Commit

Permalink
CardPool: Override all mutating Map methods, making sure _count stays…
Browse files Browse the repository at this point in the history
… in sync.
  • Loading branch information
Senryoku committed Oct 19, 2023
1 parent f54efb1 commit 72f9473
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions src/CardTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,20 +82,39 @@ export class Card {

export type DeckBasicLands = { [key in CardColor]: number };

// Implements a MultiSet using a standard Map.
export class CardPool extends Map<CardID, number> {
private _count = 0;

constructor() {
super();
}

// Set the number of copies of a card in the pool.
// Note: If count is <= 0, the card entry will be removed entirely.
set(cid: CardID, count: number) {
if (super.has(cid)) this._count -= super.get(cid)!;
super.set(cid, count);
this._count += count;
if (super.has(cid)) {
this._count -= super.get(cid)!;
if (count <= 0) super.delete(cid);
}
if (count > 0) {
super.set(cid, count);
this._count += count;
}
return this;
}

clear(): void {
super.clear();
this._count = 0;
}

delete(key: string): boolean {
const oldValue = super.get(key);
if (oldValue) this._count -= oldValue;
return super.delete(key);
}

// Remove a single copy of a card from the pool.
removeCard(cid: CardID) {
const oldValue = this.get(cid);
Expand All @@ -104,8 +123,9 @@ export class CardPool extends Map<CardID, number> {
console.trace();
throw `Called removeCard on a non-existing card (${cid}).`;
}
if (oldValue === 1) this.delete(cid);
else super.set(cid, oldValue - 1); // Purposefully bypassing our caching overload and calling super.set directly here.
// Purposefully bypassing our caching overload and calling super.set() and super.delete() directly here.
if (oldValue === 1) super.delete(cid);
else super.set(cid, oldValue - 1);
--this._count;
}

Expand Down

0 comments on commit 72f9473

Please sign in to comment.