-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathcache.js
74 lines (61 loc) · 1.32 KB
/
cache.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
"use strict";
var Cache, cacheCron, cacheCronTimeout, cacheExpiresTime, caches;
cacheExpiresTime = 0;
caches = [];
cacheCron = function() {
var currentTime = Date.now();
caches.forEach( function( cache ) {
var count = {
cached: 0,
deleted: 0
};
cache.each( function( value, key ) {
count.cached++;
if ( cache.expires[ key ] < currentTime ) {
cache.destroy( key );
count.deleted++;
}
} );
console.log( cache.name + " Cleanup:", count );
} );
cacheCronTimeout = setTimeout( cacheCron, cacheExpiresTime );
};
Cache = function( name ) {
this.cache = {};
this.expires = {};
this.name = name;
caches.push( this );
};
Cache.on = function( expiresTime ) {
cacheExpiresTime = expiresTime;
clearTimeout( cacheCronTimeout );
cacheCron();
};
Cache.prototype = {
destroy: function( key ) {
delete this.cache[ key ];
},
each: function( callback ) {
var key;
for ( key in this.cache ) {
callback( this.cache[ key ], key );
}
},
get: function( key ) {
var value = this.cache[ key ];
if ( value ) {
this.setExpire( key );
}
return value;
},
set: function( key, value ) {
if ( cacheExpiresTime ) {
this.cache[ key ] = value;
this.setExpire( key );
}
},
setExpire: function( key ) {
this.expires[ key ] = Date.now() + cacheExpiresTime;
}
};
module.exports = Cache;