1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | 'use strict';
|
13 |
|
14 | var invariant = require("fbjs/lib/invariant");
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | var LRUCache = function () {
|
28 | function LRUCache(capacity) {
|
29 | this._capacity = capacity;
|
30 | !(this._capacity > 0) ? process.env.NODE_ENV !== "production" ? invariant(false, 'LRUCache: Unable to create instance of cache with zero or negative capacity.') : invariant(false) : void 0;
|
31 | this._map = new Map();
|
32 | }
|
33 |
|
34 | var _proto = LRUCache.prototype;
|
35 |
|
36 | _proto.set = function set(key, value) {
|
37 | this._map["delete"](key);
|
38 |
|
39 | this._map.set(key, value);
|
40 |
|
41 | if (this._map.size > this._capacity) {
|
42 | var firstKey = this._map.keys().next();
|
43 |
|
44 | if (!firstKey.done) {
|
45 | this._map["delete"](firstKey.value);
|
46 | }
|
47 | }
|
48 | };
|
49 |
|
50 | _proto.get = function get(key) {
|
51 | var value = this._map.get(key);
|
52 |
|
53 | if (value != null) {
|
54 | this._map["delete"](key);
|
55 |
|
56 | this._map.set(key, value);
|
57 | }
|
58 |
|
59 | return value;
|
60 | };
|
61 |
|
62 | _proto.has = function has(key) {
|
63 | return this._map.has(key);
|
64 | };
|
65 |
|
66 | _proto["delete"] = function _delete(key) {
|
67 | this._map["delete"](key);
|
68 | };
|
69 |
|
70 | _proto.size = function size() {
|
71 | return this._map.size;
|
72 | };
|
73 |
|
74 | _proto.capacity = function capacity() {
|
75 | return this._capacity - this._map.size;
|
76 | };
|
77 |
|
78 | _proto.clear = function clear() {
|
79 | this._map.clear();
|
80 | };
|
81 |
|
82 | return LRUCache;
|
83 | }();
|
84 |
|
85 | function create(capacity) {
|
86 | return new LRUCache(capacity);
|
87 | }
|
88 |
|
89 | module.exports = {
|
90 | create: create
|
91 | }; |
\ | No newline at end of file |