Loto / src /utils /LRUCache.ts
Raí Santos
oi
4c1e4ec
/**
* LRU Cache otimizado para evitar memory leaks
*/
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) {
// Move para o final (mais recente)
this.cache.delete(key);
this.cache.set(key, value);
}
return value;
}
set(key: K, value: V): void {
if (this.cache.has(key)) {
// Atualizar valor existente
this.cache.delete(key);
this.cache.set(key, value);
return;
}
if (this.cache.size >= this.maxSize) {
// Remover o mais antigo (primeiro)
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();
}
// Método para cleanup automático baseado em tempo
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));
}
// Estatísticas de uso
getStats() {
return {
size: this.cache.size,
maxSize: this.maxSize,
usage: (this.cache.size / this.maxSize) * 100
};
}
}