Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/__tests__/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,45 @@ describe("cachedCall", () => {
expect(result).toEqual(obj);
expect(result).toBe(obj); // same reference
});

it("evicts the oldest entry when the cache reaches its size limit", () => {
const { MAX_ENTRIES, cache } = _cacheInternals;

for (let i = 0; i < MAX_ENTRIES; i++) {
cachedCall(`key-${i}`, 1000, () => i);
}
cachedCall("newest", 1000, () => "newest-value");

expect(cache.size).toBe(MAX_ENTRIES);
expect(cache.has("key-0")).toBe(false);
expect(cache.get("newest")?.value).toBe("newest-value");
});

it("recomputes an evicted entry on its next access", () => {
const { MAX_ENTRIES } = _cacheInternals;
let callCount = 0;

cachedCall("oldest", 1000, () => ++callCount);
for (let i = 1; i <= MAX_ENTRIES; i++) {
cachedCall(`key-${i}`, 1000, () => i);
}

expect(cachedCall("oldest", 1000, () => ++callCount)).toBe(2);
expect(callCount).toBe(2);
});

it("recomputing an existing key at capacity does not evict another entry", () => {
const { MAX_ENTRIES, cache } = _cacheInternals;

for (let i = 0; i < MAX_ENTRIES; i++) {
cachedCall(`key-${i}`, -1, () => i);
}
cachedCall("key-0", 1000, () => "refreshed");

expect(cache.size).toBe(MAX_ENTRIES);
expect(cache.has("key-1")).toBe(true);
expect(cache.get("key-0")?.value).toBe("refreshed");
});
});

describe("clearCache", () => {
Expand Down
13 changes: 12 additions & 1 deletion src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,24 @@
// Single-user local dashboard — no need for external cache.

const cache = new Map<string, { value: unknown; expiresAt: number }>();
const MAX_ENTRIES = 500;

function evictOldestEntry(): void {
const oldestKey = cache.keys().next().value;
if (oldestKey !== undefined) {
cache.delete(oldestKey);
}
}

export function cachedCall<T>(key: string, ttlMs: number, fn: () => T): T {
const entry = cache.get(key);
if (entry && Date.now() < entry.expiresAt) {
return entry.value as T;
}
const value = fn();
if (!cache.has(key) && cache.size >= MAX_ENTRIES) {
evictOldestEntry();
}
cache.set(key, { value, expiresAt: Date.now() + ttlMs });
return value;
}
Expand All @@ -18,4 +29,4 @@ export function clearCache(): void {
}

// Exported for testing
export const _cacheInternals = { cache };
export const _cacheInternals = { cache, MAX_ENTRIES };