-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
82 lines (68 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const LRU = require('lru-cache');
const FixedSizeCache = function (options) {
if (options && options.settings && options.settings.maxCacheSizeBytes < Infinity) {
this._maxCacheSizeBytes = options.settings.maxCacheSizeBytes;
} else {
this._maxCacheSizeBytes = 2621440;
}
this._lru = new LRU({
max: this._maxCacheSizeBytes,
length: function (json) {
return json.length * 2; //Each char occupies two bytes.
}
});
}
/**
* Stores a value in the entry with name key.
* @param {String} key
* @param {*} value
* @returns {FixedSizeCache}
*/
FixedSizeCache.prototype.set = function (key, value) {
this._lru.set(key, JSON.stringify(value));
return this;
}
/**
* Gets the value associated with key, if it exists, otherwise returns undefined.
* @param {String} key
* @returns {*}
*/
FixedSizeCache.prototype.get = function (key) {
const value = this._lru.get(key);
if (value !== undefined) {
return JSON.parse(value);
}
return undefined;
}
/**
* Returns true if for the key there is an associated value.
* @param {String} key
* @returns {boolean}
*/
FixedSizeCache.prototype.has = function (key) {
return this._lru.has(key);
}
/**
* Removes the value associated with the and the key itself.
* @param {String} key
* @returns {FixedSizeCache}
*/
FixedSizeCache.prototype.remove = function (key) {
this._lru.del(key);
return this;
}
/**
* Returns the remaining free space in the cache in bytes
* @returns {number}
*/
FixedSizeCache.prototype.getCacheMaximumCapacityInBytes = function () {
return this._maxCacheSizeBytes;
}
/**
* Returns the cache maximum capacity in bytes
* @returns {number}
*/
FixedSizeCache.prototype.getRemainingBytes = function () {
return this._maxCacheSizeBytes - this._lru.length;
}
module.exports = FixedSizeCache;