Files
bitfielder/src/utils/LRUCache.ts
2025-07-06 13:11:19 +02:00

72 lines
1.5 KiB
TypeScript

export class LRUCache<K, V> {
private maxSize: number;
private cache: Map<K, V>;
private accessOrder: K[];
constructor(maxSize: number) {
this.maxSize = maxSize;
this.cache = new Map();
this.accessOrder = [];
}
get(key: K): V | undefined {
const value = this.cache.get(key);
if (value !== undefined) {
this.markAsUsed(key);
}
return value;
}
set(key: K, value: V): void {
if (this.cache.has(key)) {
this.cache.set(key, value);
this.markAsUsed(key);
} else {
if (this.cache.size >= this.maxSize) {
this.evictLeastUsed();
}
this.cache.set(key, value);
this.accessOrder.push(key);
}
}
has(key: K): boolean {
return this.cache.has(key);
}
delete(key: K): boolean {
if (this.cache.delete(key)) {
this.removeFromAccessOrder(key);
return true;
}
return false;
}
clear(): void {
this.cache.clear();
this.accessOrder = [];
}
get size(): number {
return this.cache.size;
}
private markAsUsed(key: K): void {
this.removeFromAccessOrder(key);
this.accessOrder.push(key);
}
private removeFromAccessOrder(key: K): void {
const index = this.accessOrder.indexOf(key);
if (index > -1) {
this.accessOrder.splice(index, 1);
}
}
private evictLeastUsed(): void {
if (this.accessOrder.length > 0) {
const leastUsed = this.accessOrder.shift()!;
this.cache.delete(leastUsed);
}
}
}