|
| 1 | +/* |
| 2 | +Least recently used (LRU) - cache implementation |
| 3 | +
|
| 4 | +get(key) – Get the value (will always be positive) of the key if the key exists in the cache, otherwise return false. |
| 5 | +Complexity: O(1) |
| 6 | +
|
| 7 | +set(key, value) – Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. |
| 8 | +Complexity: O(1) |
| 9 | +*/ |
| 10 | + |
| 11 | +const DoublyLinkedList = require('../index'); |
| 12 | + |
| 13 | +class LRUCache { |
| 14 | + constructor(n) { |
| 15 | + this.size = n; |
| 16 | + this.map = new Map(); |
| 17 | + this.list = new DoublyLinkedList(); |
| 18 | + } |
| 19 | + |
| 20 | + // this method will work in O(1) |
| 21 | + set(key, value) { |
| 22 | + const data = { |
| 23 | + key, |
| 24 | + value, |
| 25 | + }; |
| 26 | + if (!this.map.has(key)) { |
| 27 | + this.list.addAtBeginning(data); |
| 28 | + this.map.set(key, this.list.head.next); |
| 29 | + |
| 30 | + if (this.list.length() > this.size) { |
| 31 | + const lastNode = this.list.tail.previous.data; |
| 32 | + this.map.delete(lastNode.key); |
| 33 | + this.list.removeAtEnd(); |
| 34 | + } |
| 35 | + } else { |
| 36 | + this.list.remove(this.map.get(key)); |
| 37 | + this.list.addAtBeginning(data); |
| 38 | + this.map.set(key, this.list.head.next); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // this method will work in O(1) |
| 43 | + get(key) { |
| 44 | + if (this.map.has(key)) { |
| 45 | + const node = this.map.get(key); |
| 46 | + const { value } = node.data; |
| 47 | + this.list.remove(node); |
| 48 | + this.list.addAtBeginning({ |
| 49 | + key, |
| 50 | + value, |
| 51 | + }); |
| 52 | + this.map.set(key, this.list.head.next); |
| 53 | + } |
| 54 | + return false; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +// const lru = new LRUCache(3); |
| 59 | +// lru.set(1, 1); |
| 60 | +// lru.set(2, 2); |
| 61 | +// lru.set(3, 3); |
| 62 | +// lru.set(4, 4); |
| 63 | +// lru.set(5, 5); |
| 64 | +// lru.set(2, 2); |
| 65 | +// lru.get(5, 5); |
| 66 | +// lru.list.display(); |
| 67 | + |
| 68 | + |
| 69 | +module.exports = { |
| 70 | + LRUCache, |
| 71 | +}; |
0 commit comments