UNPKG

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