UNPKG

2.58 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.LRUCache = void 0;
9
10var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
11
12var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
13
14var LRUCache = function () {
15 function LRUCache() {
16 var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50;
17 var destroy = arguments.length > 1 ? arguments[1] : undefined;
18 (0, _classCallCheck2.default)(this, LRUCache);
19 this.limit = void 0;
20 this.cache = void 0;
21 this.destroy = void 0;
22 this.order = void 0;
23 this.limit = limit;
24 this.destroy = destroy || this.defaultDestroy;
25 this.order = [];
26 this.clear();
27 }
28
29 (0, _createClass2.default)(LRUCache, [{
30 key: "clear",
31 value: function clear() {
32 var _this = this;
33
34 this.order.forEach(function (key) {
35 _this.delete(key);
36 });
37 this.cache = {};
38 this.order = [];
39 }
40 }, {
41 key: "get",
42 value: function get(key) {
43 var value = this.cache[key];
44
45 if (value) {
46 this.deleteOrder(key);
47 this.appendOrder(key);
48 }
49
50 return value;
51 }
52 }, {
53 key: "set",
54 value: function set(key, value) {
55 if (!this.cache[key]) {
56 if (Object.keys(this.cache).length === this.limit) {
57 this.delete(this.order[0]);
58 }
59
60 this.cache[key] = value;
61 this.appendOrder(key);
62 } else {
63 this.delete(key);
64 this.cache[key] = value;
65 this.appendOrder(key);
66 }
67 }
68 }, {
69 key: "delete",
70 value: function _delete(key) {
71 var value = this.cache[key];
72
73 if (value) {
74 this.deleteCache(key);
75 this.deleteOrder(key);
76 this.destroy(value, key);
77 }
78 }
79 }, {
80 key: "deleteCache",
81 value: function deleteCache(key) {
82 delete this.cache[key];
83 }
84 }, {
85 key: "deleteOrder",
86 value: function deleteOrder(key) {
87 var index = this.order.findIndex(function (o) {
88 return o === key;
89 });
90
91 if (index >= 0) {
92 this.order.splice(index, 1);
93 }
94 }
95 }, {
96 key: "appendOrder",
97 value: function appendOrder(key) {
98 this.order.push(key);
99 }
100 }, {
101 key: "defaultDestroy",
102 value: function defaultDestroy(value, key) {
103 return null;
104 }
105 }]);
106 return LRUCache;
107}();
108
109exports.LRUCache = LRUCache;
110//# sourceMappingURL=lru_cache.js.map
\No newline at end of file