Created
September 28, 2022 20:55
-
-
Save jhurliman/3ab56dac43c97902a2e25755485431d9 to your computer and use it in GitHub Desktop.
LRU cache in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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