Skip to content

Commit

Permalink
feat: add values
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Dec 30, 2024
1 parent 1de04a0 commit daf6929
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/weak-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | { key: string }, { value: string }>([
["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);
});
});
9 changes: 9 additions & 0 deletions src/weak-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,13 @@ export class WeakCache<K extends {}, V extends WeakKey = WeakKey> {
}
return this;
}

public *values(): IterableIterator<V> {
for (const ref of this._refs_.values()) {
const value = ref.deref();
if (value) {
yield value;
}
}
}
}

0 comments on commit daf6929

Please sign in to comment.