UNPKG

2.13 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 *
8 * @emails oncall+relay
9 * @format
10 */
11// flowlint ambiguous-object-type:error
12'use strict';
13
14var invariant = require("fbjs/lib/invariant");
15
16/**
17 * JS maps (both plain objects and Map) maintain key insertion
18 * order, which means there is an easy way to simulate LRU behavior
19 * that should also perform quite well:
20 *
21 * To insert a new value, first delete the key from the inner _map,
22 * then _map.set(k, v). By deleting and reinserting, you ensure that the
23 * map sees the key as the last inserted key.
24 *
25 * Get does the same: if the key is present, delete and reinsert it.
26 */
27var LRUCache = /*#__PURE__*/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
85function create(capacity) {
86 return new LRUCache(capacity);
87}
88
89module.exports = {
90 create: create
91};
\No newline at end of file