Skip to content

Commit 83dbd89

Browse files
committed
refactor(cache): add size() method to TTLCache
Fixes JhaSourav07#301
1 parent e15a46a commit 83dbd89

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

lib/cache.test.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,44 @@ describe('TTLCache', () => {
9696
});
9797
});
9898

99+
describe('size()', () => {
100+
it('returns 0 for an empty cache', () => {
101+
const cache = new TTLCache<number>();
102+
expect(cache.size()).toBe(0);
103+
cache.destroy();
104+
});
105+
106+
it('counts only entries before expiry', () => {
107+
vi.useFakeTimers();
108+
const cache = new TTLCache<number>();
109+
cache.set('a', 1, 10_000);
110+
cache.set('b', 2, 20_000);
111+
expect(cache.size()).toBe(2);
112+
113+
vi.advanceTimersByTime(15_000);
114+
expect(cache.size()).toBe(1);
115+
cache.destroy();
116+
});
117+
118+
it('returns 0 when all entries have expired (after TTL expiry)', () => {
119+
vi.useFakeTimers();
120+
const cache = new TTLCache<number>();
121+
cache.set('a', 1, 10_000);
122+
vi.advanceTimersByTime(15_000);
123+
expect(cache.size()).toBe(0);
124+
cache.destroy();
125+
});
126+
127+
it('returns 0 after clear() is called', () => {
128+
const cache = new TTLCache<number>();
129+
cache.set('a', 1, 10_000);
130+
expect(cache.size()).toBe(1);
131+
cache.clear();
132+
expect(cache.size()).toBe(0);
133+
cache.destroy();
134+
});
135+
});
136+
99137
describe('destroy()', () => {
100138
it('clears the store and stops the interval', () => {
101139
vi.useFakeTimers();

lib/cache.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ export class TTLCache<T> {
6868
this.store.clear();
6969
}
7070

71+
size(): number {
72+
this.sweep();
73+
return this.store.size;
74+
}
75+
7176
destroy(): void {
7277
if (this.cleanupInterval) {
7378
clearInterval(this.cleanupInterval);

0 commit comments

Comments
 (0)