Created
July 22, 2025 20:34
-
-
Save Sheraff/34b0f6eaf507833f6de851c954a0cb07 to your computer and use it in GitHub Desktop.
LRU cache as a JS Map
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 LRUMap<TKey, TValue> extends Map<TKey, TValue> { | |
| constructor(max: number) { | |
| super() | |
| const get = this.get.bind(this) | |
| const set = this.set.bind(this) | |
| this.get = (key: TKey) => { | |
| const item = get(key) | |
| if (item !== undefined) { | |
| // refresh key | |
| this.delete(key) | |
| set(key, item) | |
| } | |
| return item | |
| } | |
| this.set = (key: TKey, val: TValue) => { | |
| // refresh key | |
| if (this.has(key)) this.delete(key) | |
| // evict oldest | |
| else if (this.size == max) this.delete(this.keys().next().value!) | |
| set(key, val) | |
| return this | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment