| 1 | export class CacheMap<K, V> implements Map<K, V> { |
| 2 | private cache: Map<K, V> |
| 3 | private keysInUse: K[] |
| 4 | private maxCacheSize: number |
| 5 | |
| 6 | constructor(maxCacheSize = 1000) { |
| 7 | this.maxCacheSize = maxCacheSize |
| 8 | this.cache = new Map<K, V>() |
| 9 | this.keysInUse = [] |
| 10 | } |
| 11 | |
| 12 | get(key: K) { |
| 13 | if (!this.cache.has(key)) { |
| 14 | return undefined |
| 15 | } |
| 16 | this.updateKeyUsage(key) |
| 17 | return this.cache.get(key) |
| 18 | } |
| 19 | |
| 20 | set(key: K, value: V) { |
| 21 | if (!this.cache.has(key) && this.cache.size === this.maxCacheSize) { |
| 22 | this.evictLeastRecentlyUsed() |
| 23 | } |
| 24 | this.cache.set(key, value) |
| 25 | this.updateKeyUsage(key) |
| 26 | return this |
| 27 | } |
| 28 | |
| 29 | delete(key: K) { |
| 30 | const result = this.cache.delete(key) |
| 31 | if (result) { |
| 32 | const index = this.keysInUse.indexOf(key) |
| 33 | if (index !== -1) { |
| 34 | this.keysInUse.splice(index, 1) |
| 35 | } |
| 36 | } |
| 37 | return result |
| 38 | } |
| 39 | |
| 40 | private updateKeyUsage(key: K) { |
| 41 | const index = this.keysInUse.indexOf(key) |
| 42 | if (index !== -1) { |
| 43 | this.keysInUse.splice(index, 1) |
| 44 | } |
| 45 | this.keysInUse.push(key) |
| 46 | } |
| 47 | |
| 48 | private evictLeastRecentlyUsed() { |
| 49 | const keyToEvict = this.keysInUse.shift() |
| 50 | if (keyToEvict !== undefined) { |
| 51 | this.cache.delete(keyToEvict) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | clear() { |
| 56 | this.cache.clear() |
| 57 | this.keysInUse = [] |
| 58 | } |
| 59 | |
| 60 | has(key: K): boolean { |
nothing calls this directly
no outgoing calls
no test coverage detected