Created
October 17, 2025 16:52
-
-
Save oscarmarina/e56ebcb91cd4577d7be4b438dbe72469 to your computer and use it in GitHub Desktop.
LRU cache
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
| export class LRUCache extends Map { | |
| constructor(maxSize) { | |
| if (maxSize <= 0) { | |
| throw new Error('maxSize must be greater than 0'); | |
| } | |
| super(); | |
| this.maxSize = maxSize; | |
| } | |
| set(key, value) { | |
| super.delete(key); | |
| super.set(key, value); | |
| if (this.size > this.maxSize) { | |
| const keyToDelete = this.keys().next().value; | |
| if (keyToDelete !== undefined) { | |
| this.delete(keyToDelete); | |
| } | |
| } | |
| return this; | |
| } | |
| get(key) { | |
| const value = super.get(key); | |
| if (value !== undefined) { | |
| // Deleting and setting the value again ensures the key is at the end of the LRU queue | |
| this.delete(key); | |
| this.set(key, value); | |
| } | |
| return value; | |
| } | |
| } |
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
| export class LRUCache<K, V> extends Map<K, V> { | |
| constructor(public readonly maxSize: number) { | |
| if (maxSize <= 0) { | |
| throw new Error('maxSize must be greater than 0'); | |
| } | |
| super(); | |
| } | |
| override set(key: K, value: V): this { | |
| super.delete(key); | |
| super.set(key, value); | |
| if (this.size > this.maxSize) { | |
| const keyToDelete = this.keys().next().value; | |
| if (keyToDelete !== undefined) { | |
| this.delete(keyToDelete); | |
| } | |
| } | |
| return this; | |
| } | |
| override get(key: K): V | undefined { | |
| const value = super.get(key); | |
| if (value !== undefined) { | |
| // Deleting and setting the value again ensures the key is at the end of the LRU queue | |
| this.delete(key); | |
| this.set(key, value); | |
| } | |
| return value; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment