|
|
|
|
|
|
|
|
|
export class LRUCache<K, V> { |
|
private maxSize: number; |
|
private cache = new Map<K, V>(); |
|
|
|
constructor(maxSize: number = 10) { |
|
this.maxSize = maxSize; |
|
} |
|
|
|
get(key: K): V | undefined { |
|
const value = this.cache.get(key); |
|
if (value !== undefined) { |
|
|
|
this.cache.delete(key); |
|
this.cache.set(key, value); |
|
} |
|
return value; |
|
} |
|
|
|
set(key: K, value: V): void { |
|
if (this.cache.has(key)) { |
|
|
|
this.cache.delete(key); |
|
this.cache.set(key, value); |
|
return; |
|
} |
|
|
|
if (this.cache.size >= this.maxSize) { |
|
|
|
const firstKey = this.cache.keys().next().value; |
|
this.cache.delete(firstKey); |
|
} |
|
|
|
this.cache.set(key, value); |
|
} |
|
|
|
has(key: K): boolean { |
|
return this.cache.has(key); |
|
} |
|
|
|
delete(key: K): boolean { |
|
return this.cache.delete(key); |
|
} |
|
|
|
clear(): void { |
|
this.cache.clear(); |
|
} |
|
|
|
size(): number { |
|
return this.cache.size; |
|
} |
|
|
|
keys(): IterableIterator<K> { |
|
return this.cache.keys(); |
|
} |
|
|
|
values(): IterableIterator<V> { |
|
return this.cache.values(); |
|
} |
|
|
|
|
|
cleanup(maxAge: number = 5 * 60 * 1000): void { |
|
const now = Date.now(); |
|
const toDelete: K[] = []; |
|
|
|
this.cache.forEach((value, key) => { |
|
if (typeof value === 'object' && value !== null && 'timestamp' in value) { |
|
const timestamp = (value as any).timestamp; |
|
if (now - timestamp > maxAge) { |
|
toDelete.push(key); |
|
} |
|
} |
|
}); |
|
|
|
toDelete.forEach(key => this.cache.delete(key)); |
|
} |
|
|
|
|
|
getStats() { |
|
return { |
|
size: this.cache.size, |
|
maxSize: this.maxSize, |
|
usage: (this.cache.size / this.maxSize) * 100 |
|
}; |
|
} |
|
} |
|
|