opnet
Version:
The perfect library for building Bitcoin-based applications.
31 lines (27 loc) • 829 B
text/typescript
export class LRUCache<K, V> {
private readonly cache: Map<K, V>;
private readonly maxSize: number;
constructor(maxSize: number) {
this.cache = new Map();
this.maxSize = maxSize;
}
public 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;
}
public set(key: K, value: V): void {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
if (firstKey !== undefined) {
this.cache.delete(firstKey);
}
}
this.cache.set(key, value);
}
}