-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CacheMap.js
69 lines (64 loc) · 1.59 KB
/
CacheMap.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
/**
* Cache for images, audio, or any other kind of resource
* @param manager
* @constructor
*/
function CacheMap(manager) {
this.manager = manager;
this._inner = {};
this._lastRemovedEntries = {};
this.updateTicks = 0;
this.lastCheckTTL = 0;
this.delayCheckTTL = 100.0;
this.updateSeconds = Date.now();
}
/**
* checks ttl of all elements and removes dead ones
*/
CacheMap.prototype.checkTTL = function () {
var cache = this._inner;
var temp = this._lastRemovedEntries;
if (!temp) {
temp = [];
this._lastRemovedEntries = temp;
}
for (var key in cache) {
var entry = cache[key];
if (!entry.isStillAlive()) {
temp.push(entry);
}
}
for (var i = 0; i < temp.length; i++) {
temp[i].free(true);
}
temp.length = 0;
};
/**
* cache item
* @param key url of cache element
* @returns {*|null}
*/
CacheMap.prototype.getItem = function (key) {
var entry = this._inner[key];
if (entry) {
return entry.item;
}
return null;
};
CacheMap.prototype.clear = function () {
var keys = Object.keys(this._inner);
for (var i = 0; i < keys.length; i++) {
this._inner[keys[i]].free();
}
};
CacheMap.prototype.setItem = function (key, item) {
return new CacheEntry(this, key, item).allocate();
};
CacheMap.prototype.update = function(ticks, delta) {
this.updateTicks += ticks;
this.updateSeconds += delta;
if (this.updateSeconds >= this.delayCheckTTL + this.lastCheckTTL) {
this.lastCheckTTL = this.updateSeconds;
this.checkTTL();
}
};