-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (80 loc) · 2.28 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
let cache = {};
const isDefined = (item) => {
return typeof item !== 'undefined';
}
, isExpired = (key) => {
const currentTime = new Date();
let expired;
if (cache[key].expires === Infinity){
expired = false;
} else {
expired = !!(currentTime.getTime() >= cache[key].expires.getTime() || cache[key].expires === 0);
}
if (expired){
// clear this item from cache
delete cache[key];
}
return expired;
}
, getFromCache = (key) => {
if (isDefined(cache[key]) && !isExpired(key)) {
cache[key].uses++;
return cache[key].data;
} else {
return null;
}
}
, cacheEntries = () => {
const obj = {};
Object.keys(cache).forEach((item) => {
obj[item] = { expires: cache[item].expires, uses: cache[item].uses };
});
return obj;
}
, clearCache = (pruneThreshold) => {
if (isDefined(pruneThreshold)) {
Object.keys(cache).forEach((item) => {
if (cache[item].uses <= pruneThreshold && cache[item].expires !== Infinity){
delete cache[item];
}
});
} else {
cache = {};
}
}
, pruneCache = (threshold) => {
return clearCache(threshold);
}
, removeFromCache = (key) => {
if (!isDefined(key)) {
throw new Error('key must be passed in');
}
if (isDefined(cache[key])) {
return delete cache[key];
} else {
return false;
}
}
, addToCache = (key, object, expiresIn) => {
const expires = expiresIn || 300000;
cache[key] = {
data: object
, expires: 0
, uses: 0
};
// permenant cache option... pass in Infinity as the expires period
if (expires === Infinity){
cache[key].expires = Infinity;
} else {
cache[key].expires = new Date(new Date().getTime() + expires);
}
};
module.exports = {
get: getFromCache
, clear: clearCache
, remove: removeFromCache
, entries: cacheEntries
, add: addToCache
, prune: pruneCache
};