Skip to content

Commit

Permalink
feat: add clear dispose callback
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Dec 23, 2024
1 parent 4f04fd9 commit c8484c2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
31 changes: 31 additions & 0 deletions src/weak-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,37 @@ describe("WeakCache", () => {
expect(cache.size).toBe(0);
});

it("should clear cache with dispose", () => {
const cache = new WeakCache();
const key = "key";
const valueDisposeSpy = vi.fn();
const value = { dispose: valueDisposeSpy, value: "value" };
const objectKey = { key: "key" };
const objectValueDisposeSpy = vi.fn();
const objectValue = { dispose: objectValueDisposeSpy, value: "value" };

cache.set(key, value);
cache.set(objectKey, objectValue);

expect(cache.has(key)).toEqual(true);
expect(cache.get(key)).toEqual(value);
expect(cache.has(objectKey)).toEqual(true);
expect(cache.get(objectKey)).toEqual(objectValue);
expect(cache.size).toBe(2);

const clearSpy = vi.fn(x => x.dispose());
cache.clear(clearSpy);

expect(clearSpy).toHaveBeenCalledTimes(2);
expect(cache.has(key)).toEqual(false);
expect(cache.get(key)).toBeUndefined();
expect(valueDisposeSpy).toHaveBeenCalledTimes(1);
expect(cache.has(objectKey)).toEqual(false);
expect(cache.get(objectKey)).toBeUndefined();
expect(objectValueDisposeSpy).toHaveBeenCalledTimes(1);
expect(cache.size).toBe(0);
});

it("should ensure value", () => {
const cache = new WeakCache();
const key = "key";
Expand Down
6 changes: 5 additions & 1 deletion src/weak-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,13 @@ export class WeakCache<K extends {}, V extends WeakKey = WeakKey> {
}
}

public clear(): void {
public clear(dispose?: (value: V) => void): void {
for (const ref of this._refs_.values()) {
this._registry_.unregister(ref);
if (dispose) {
const value = ref.deref();
if (value) dispose(value);
}
}
this._refs_.clear();
}
Expand Down

0 comments on commit c8484c2

Please sign in to comment.