forked from ptarjan/node-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (70 loc) · 1.52 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
var cache = {}
function now() { return (new Date).getTime(); }
var debug = false;
var hitCount = 0;
var missCount = 0;
exports.put = function(key, value, time, timeoutCallback) {
if (debug) console.log('caching: '+key+' = '+value+' (@'+time+')');
var oldRecord = cache[key];
if (oldRecord) {
clearTimeout(oldRecord.timeout);
}
var expire = time + now();
var record = {value: value, expire: expire};
if (!isNaN(expire)) {
var timeout = setTimeout(function() {
exports.del(key);
if (typeof timeoutCallback === 'function') {
timeoutCallback(key);
}
}, time);
record.timeout = timeout;
}
cache[key] = record;
}
exports.del = function(key) {
delete cache[key];
}
exports.clear = function() {
cache = {};
}
exports.get = function(key) {
var data = cache[key];
if (typeof data != "undefined") {
if (isNaN(data.expire) || data.expire >= now()) {
if (debug) hitCount++;
return data.value;
} else {
// free some space
if (debug) missCount++;
exports.del(key);
}
}
return null;
}
exports.size = function() {
var size = 0, key;
for (key in cache) {
if (cache.hasOwnProperty(key))
if (exports.get(key) !== null)
size++;
}
return size;
}
exports.memsize = function() {
var size = 0, key;
for (key in cache) {
if (cache.hasOwnProperty(key))
size++;
}
return size;
}
exports.debug = function(bool) {
debug = bool;
}
exports.hits = function() {
return hitCount;
}
exports.misses = function() {
return missCount;
}