This repository has been archived by the owner on May 26, 2020. It is now read-only.
forked from ptarjan/node-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
124 lines (104 loc) · 2.27 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
'use strict';
var cache = Object.create(null);
var debug = false;
var hitCount = 0;
var missCount = 0;
var size = 0;
exports.put = function(key, value, time, timeoutCallback) {
if (debug) {
console.log('caching: %s = %j (@%s)', key, value, time);
}
if (typeof time !== 'undefined' && (typeof time !== 'number' || isNaN(time) || time <= 0)) {
throw new Error('Cache timeout must be a positive number');
} else if (typeof timeoutCallback !== 'undefined' && typeof timeoutCallback !== 'function') {
throw new Error('Cache timeout callback must be a function');
}
var oldRecord = cache[key];
if (oldRecord) {
clearTimeout(oldRecord.timeout);
} else {
size++;
}
var record = {
value: value,
expire: time + Date.now()
};
if (!isNaN(record.expire)) {
record.timeout = setTimeout(function() {
exports.del(key);
if (timeoutCallback) {
timeoutCallback(key);
}
}, time);
}
cache[key] = record;
return value;
};
exports.del = function(key) {
var canDelete = true;
var oldRecord = cache[key];
if (oldRecord) {
clearTimeout(oldRecord.timeout);
if (!isNaN(oldRecord.expire) && oldRecord.expire < Date.now()) {
canDelete = false;
}
} else {
canDelete = false;
}
if (canDelete) {
size--;
delete cache[key];
}
return canDelete;
};
exports.clear = function() {
for (var key in cache) {
clearTimeout(cache[key].timeout);
}
size = 0;
cache = Object.create(null);
if (debug) {
hitCount = 0;
missCount = 0;
}
};
exports.get = function(key) {
var data = cache[key];
if (typeof data != "undefined") {
if (isNaN(data.expire) || data.expire >= Date.now()) {
if (debug) hitCount++;
return data.value;
} else {
// free some space
if (debug) missCount++;
size--;
delete cache[key];
}
} else if (debug) {
missCount++;
}
return undefined;
};
exports.size = function() {
return size;
};
exports.memsize = function() {
var size = 0,
key;
for (key in cache) {
size++;
}
return size;
};
exports.debug = function(bool) {
debug = bool;
};
exports.hits = function() {
return hitCount;
};
exports.misses = function() {
return missCount;
};
exports.keys = function() {
return Object.keys(cache);
};