forked from ariatemplates/snippets.ariatemplates.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
68 lines (59 loc) · 1.47 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
/**
* Cache utility class with First In First Out mecanism
*/
var Cache = module.exports = (function() {
var DEFAULT_CACHE_SIZE = 100,
stack = [],
cache = {},
debug;
var log = function() {
if (debug) {
console.log.apply(console, arguments);
}
};
function Cache(options) {
debug = (options && options.debug) || false;
this.max_size = (options && options.size) || DEFAULT_CACHE_SIZE;
log("[Cache]", "Initialized with size:", this.max_size);
}
Cache.prototype = {
put: function(key, item) {
var to_remove;
if (this.size() >= this.max_size) {
to_remove = stack.shift();
log("[Cache]", "Size Limit Warning", "purging", to_remove);
this.del(to_remove);
}
if (!cache[key]) {
log("[Cache]", "adding item", key);
stack.push(key);
} else {
log("[Cache]", "updating item", key);
}
cache[key] = item;
return item;
},
get: function(key) {
return cache[key] || null;
},
del: function(key) {
stack.splice(stack.indexOf(key), 1)
delete cache[key];
},
clear: function() {
cache = {};
stack = [];
log("[Cache]", "Cache has been sucessfully flushed");
},
size: function() {
return stack.length;
},
stats: function() {
return {
status: "Cache Info: " + this.size() + " items.",
keys: JSON.stringify(stack, null, 2)
}
}
};
return Cache;
})();