| 1 | class LRUCache { |
| 2 | // LRU Cache to store a given capacity of data |
| 3 | #capacity |
| 4 | |
| 5 | /** |
| 6 | * @param {number} capacity - the capacity of LRUCache |
| 7 | * @returns {LRUCache} - sealed |
| 8 | */ |
| 9 | constructor(capacity) { |
| 10 | if (!Number.isInteger(capacity) || capacity < 0) { |
| 11 | throw new TypeError('Invalid capacity') |
| 12 | } |
| 13 | |
| 14 | this.#capacity = ~~capacity |
| 15 | this.misses = 0 |
| 16 | this.hits = 0 |
| 17 | this.cache = new Map() |
| 18 | |
| 19 | return Object.seal(this) |
| 20 | } |
| 21 | |
| 22 | get info() { |
| 23 | return Object.freeze({ |
| 24 | misses: this.misses, |
| 25 | hits: this.hits, |
| 26 | capacity: this.capacity, |
| 27 | size: this.size |
| 28 | }) |
| 29 | } |
| 30 | |
| 31 | get size() { |
| 32 | return this.cache.size |
| 33 | } |
| 34 | |
| 35 | get capacity() { |
| 36 | return this.#capacity |
| 37 | } |
| 38 | |
| 39 | set capacity(newCapacity) { |
| 40 | if (newCapacity < 0) { |
| 41 | throw new RangeError('Capacity should be greater than 0') |
| 42 | } |
| 43 | |
| 44 | if (newCapacity < this.capacity) { |
| 45 | let diff = this.capacity - newCapacity |
| 46 | |
| 47 | while (diff--) { |
| 48 | this.#removeLeastRecentlyUsed() |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | this.#capacity = newCapacity |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * delete oldest key existing in map by the help of iterator |
| 57 | */ |
| 58 | #removeLeastRecentlyUsed() { |
| 59 | this.cache.delete(this.cache.keys().next().value) |
| 60 | } |
nothing calls this directly
no outgoing calls
no test coverage detected