Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created September 28, 2022 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhurliman/3ab56dac43c97902a2e25755485431d9 to your computer and use it in GitHub Desktop.
Save jhurliman/3ab56dac43c97902a2e25755485431d9 to your computer and use it in GitHub Desktop.
LRU cache in TypeScript
class LruCache<T> {
private values = new Map<string, T>();
constructor(private maxEntries = 10) {}
public get(key: string): T | undefined {
const entry = this.values.get(key);
if (entry != undefined) {
this.values.delete(key);
this.values.set(key, entry);
}
return entry;
}
public set(key: string, value: T): void {
if (this.values.size >= this.maxEntries) {
const keyToDelete = this.values.keys().next().value as string;
this.values.delete(keyToDelete);
}
this.values.delete(key);
this.values.set(key, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment