auto-claude: subtask-1-1 - Add maxSize parameter and access tracking to Cache

This commit is contained in:
2026-01-25 06:31:54 +01:00
parent eec1758827
commit db13754e24
5 changed files with 331 additions and 7 deletions
+36 -6
View File
@@ -2,35 +2,65 @@ type CacheItem<T> = {
value: T;
timestamp: number;
ttl: number;
lastAccessed: number;
};
class Cache {
private storage: Map<string, CacheItem<any>>;
private readonly defaultTTL: number;
private readonly maxSize?: number;
constructor(defaultTTL = 5 * 60 * 1000) { // 5 minutes default TTL
constructor(defaultTTL = 5 * 60 * 1000, maxSize?: number) { // 5 minutes default TTL
this.storage = new Map();
this.defaultTTL = defaultTTL;
this.maxSize = maxSize;
}
set<T>(key: string, value: T, ttl = this.defaultTTL): void {
const now = Date.now();
// If maxSize is set and cache is full, evict least recently used item
if (this.maxSize && this.storage.size >= this.maxSize && !this.storage.has(key)) {
this.evictLRU();
}
this.storage.set(key, {
value,
timestamp: Date.now(),
ttl
timestamp: now,
ttl,
lastAccessed: now
});
}
private evictLRU(): void {
let lruKey: string | null = null;
let lruTime = Infinity;
for (const [key, item] of this.storage.entries()) {
if (item.lastAccessed < lruTime) {
lruTime = item.lastAccessed;
lruKey = key;
}
}
if (lruKey) {
this.storage.delete(lruKey);
}
}
get<T>(key: string): T | null {
const item = this.storage.get(key);
if (!item) return null;
if (Date.now() > item.timestamp + item.ttl) {
this.storage.delete(key);
return null;
}
// Update last accessed time for LRU tracking
item.lastAccessed = Date.now();
return item.value;
}