* Adds or updates an item in the cache. If the cache exceeds maxSize, * the least recently used item is evicted. * @param key The key of the item to set. * @param value The value to associate with the key.
(key: K, value: V)
| 34 | * @param value The value to associate with the key. |
| 35 | */ |
| 36 | set(key: K, value: V): void { |
| 37 | // If key already exists, delete it first to update its position |
| 38 | if (this.cache.has(key)) { |
| 39 | this.cache.delete(key) |
| 40 | } |
| 41 | // Check if cache is full before adding the new item |
| 42 | else if (this.cache.size >= this.maxSize) { |
| 43 | // Evict the least recently used item (the first item in the Map's iteration order) |
| 44 | const oldestKey = this.cache.keys().next().value |
| 45 | if (oldestKey !== undefined) { |
| 46 | // Should always be defined if size >= maxSize > 0 |
| 47 | this.cache.delete(oldestKey) |
| 48 | } |
| 49 | } |
| 50 | // Add the new item (or re-add the updated item) |
| 51 | this.cache.set(key, value) |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Returns the current number of items in the cache. |