123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- var Node = _createClass(function Node(key, value) {
- var next = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- var prev = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
- _classCallCheck(this, Node);
- this.key = key;
- this.value = value;
- this.next = next;
- this.prev = prev;
- });
- var LRUCache = function () {
-
- function LRUCache() {
- var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
- _classCallCheck(this, LRUCache);
- this.size = 0;
- this.limit = limit;
- this.head = null;
- this.tail = null;
- this.cache = {};
- }
-
- _createClass(LRUCache, [{
- key: "put",
- value: function put(key, value) {
- this.ensureLimit();
- if (!this.head) {
- this.head = this.tail = new Node(key, value);
- } else {
- var node = new Node(key, value, this.head);
- this.head.prev = node;
- this.head = node;
- }
- this.cache[key] = this.head;
- this.size++;
- }
- }, {
- key: "get",
- value: function get(key) {
- if (this.cache[key]) {
- var value = this.cache[key].value;
- this.remove(key);
- this.put(key, value);
- return value;
- }
- console.log("Item not available in cache for key ".concat(key));
- }
- }, {
- key: "ensureLimit",
- value: function ensureLimit() {
- if (this.size === this.limit) {
- this.remove(this.tail.key);
- }
- }
- }, {
- key: "remove",
- value: function remove(key) {
- var node = this.cache[key];
- if (node.prev !== null) {
- node.prev.next = node.next;
- } else {
- this.head = node.next;
- }
- if (node.next !== null) {
- node.next.prev = node.prev;
- } else {
- this.tail = node.prev;
- }
- delete this.cache[key];
- this.size--;
- }
- }, {
- key: "clear",
- value: function clear() {
- this.head = null;
- this.tail = null;
- this.size = 0;
- this.cache = {};
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }]);
- return LRUCache;
- }();
- export { LRUCache as default };
|