Skip to content

Instantly share code, notes, and snippets.

@itsashis4u
Created June 19, 2021 19:45
Show Gist options
  • Save itsashis4u/a3925b33b118906791b709d707be6365 to your computer and use it in GitHub Desktop.
Save itsashis4u/a3925b33b118906791b709d707be6365 to your computer and use it in GitHub Desktop.
Simple LRU (Least Recently Used) cache implementation using TypeScript
interface LRUType<K, V> extends Iterable<[K, V]> {
get(key: K): V | undefined;
readonly size: number;
set(key: K, value: V): LRUType<K, V>;
delete(key): boolean;
has(key): boolean;
keys(): IterableIterator<K>;
}
class LRU<K, V> {
max: number;
cache: LRUType<K, V>;
constructor(max: number) {
this.max = max;
this.cache = new Map<K, V>();
}
get(key: K): V {
const item = this.cache.get(key);
if (item) {
this.cache.delete(key);
this.cache.set(key, item);
}
return item;
}
set(key: K, value: V): void {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size === this.max) {
this.cache.delete(this.first());
}
this.cache.set(key, value);
}
first(): V {
return this.cache.keys().next().value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment