diff --git a/src/weak-cache.test.ts b/src/weak-cache.test.ts index c76baf5..3a4389a 100644 --- a/src/weak-cache.test.ts +++ b/src/weak-cache.test.ts @@ -226,4 +226,24 @@ describe("WeakCache", () => { cache.set("key", "value"); }).toThrowError(); }); + + it("should get alive values of cache", async () => { + const value = { value: "value" }; + const cache = new WeakCache([ + ["key", { value: "value" }], + [{ key: "key" }, { value: "value" }], + [{ key: "key" }, { value: "value" }], + [{ key: "key" }, value], + ["key2", value], + ]); + + expect(cache.size).toBeGreaterThan(0); + expect([...cache.values()].length).toBeGreaterThan(0); + + await waitGC(); + + expect(cache.size).toBe(1); + expect([...cache.values()].length).toBe(1); + expect(cache.values().next().value).toBe(value); + }); }); diff --git a/src/weak-cache.ts b/src/weak-cache.ts index 77ac865..353c5dd 100644 --- a/src/weak-cache.ts +++ b/src/weak-cache.ts @@ -97,4 +97,13 @@ export class WeakCache { } return this; } + + public *values(): IterableIterator { + for (const ref of this._refs_.values()) { + const value = ref.deref(); + if (value) { + yield value; + } + } + } }