Last active
November 17, 2025 20:56
-
-
Save dherges/86012049be7b1263b2e594134ff5816a to your computer and use it in GitHub Desktop.
Simple 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: Map<string, T> = new Map<string, T>(); | |
| private maxEntries: number = 20; | |
| public get(key: string): T { | |
| const hasKey = this.values.has(key); | |
| let entry: T; | |
| if (hasKey) { | |
| // peek the entry, re-insert for LRU strategy | |
| entry = this.values.get(key); | |
| this.values.delete(key); | |
| this.values.set(key, entry); | |
| } | |
| return entry; | |
| } | |
| public put(key: string, value: T) { | |
| if (this.values.size >= this.maxEntries) { | |
| // least-recently used cache eviction strategy | |
| const keyToDelete = this.values.keys().next().value; | |
| this.values.delete(keyToDelete); | |
| } | |
| this.values.set(key, value); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@adaptive-shield-matrix
Consider to learn a bit more