UNPKG

cione-comp-lib

Version:

`$ yarn add cione-comp-lib` 或者 `$ npm i cione-comp-lib -S`

106 lines (105 loc) 2.47 kB
var Entry = function() { function Entry2(val) { this.value = val; } return Entry2; }(); var LinkedList = function() { function LinkedList2() { this._len = 0; } LinkedList2.prototype.insert = function(val) { var entry = new Entry(val); this.insertEntry(entry); return entry; }; LinkedList2.prototype.insertEntry = function(entry) { if (!this.head) { this.head = this.tail = entry; } else { this.tail.next = entry; entry.prev = this.tail; entry.next = null; this.tail = entry; } this._len++; }; LinkedList2.prototype.remove = function(entry) { var prev = entry.prev; var next = entry.next; if (prev) { prev.next = next; } else { this.head = next; } if (next) { next.prev = prev; } else { this.tail = prev; } entry.next = entry.prev = null; this._len--; }; LinkedList2.prototype.len = function() { return this._len; }; LinkedList2.prototype.clear = function() { this.head = this.tail = null; this._len = 0; }; return LinkedList2; }(); var LRU = function() { function LRU2(maxSize) { this._list = new LinkedList(); this._maxSize = 10; this._map = {}; this._maxSize = maxSize; } LRU2.prototype.put = function(key, value) { var list = this._list; var map = this._map; var removed = null; if (map[key] == null) { var len = list.len(); var entry = this._lastRemovedEntry; if (len >= this._maxSize && len > 0) { var leastUsedEntry = list.head; list.remove(leastUsedEntry); delete map[leastUsedEntry.key]; removed = leastUsedEntry.value; this._lastRemovedEntry = leastUsedEntry; } if (entry) { entry.value = value; } else { entry = new Entry(value); } entry.key = key; list.insertEntry(entry); map[key] = entry; } return removed; }; LRU2.prototype.get = function(key) { var entry = this._map[key]; var list = this._list; if (entry != null) { if (entry !== list.tail) { list.remove(entry); list.insertEntry(entry); } return entry.value; } }; LRU2.prototype.clear = function() { this._list.clear(); this._map = {}; }; LRU2.prototype.len = function() { return this._list.len(); }; return LRU2; }(); var LRUCache = LRU; export { Entry, LinkedList, LRUCache as default };