-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCacheEntry.js
80 lines (75 loc) · 2.16 KB
/
CacheEntry.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
//-----------------------------------------------------------------------------
/**
* The resource class. Allows to be collected as a garbage if not use for some time or ticks
*
* @class CacheEntry
* @constructor
* @param {ResourceManager} resource manager
* @param {string} key, url of the resource
* @param {string} item - Bitmap, HTML5Audio, WebAudio - whatever you want to store in the cache
*/
function CacheEntry(cache, key, item) {
this.cache = cache;
this.key = key;
this.item = item;
this.cached = false;
this.touchTicks = 0;
this.touchSeconds = 0;
this.ttlTicks = 0;
this.ttlSeconds = 0;
this.freedByTTL = false;
}
/**
* frees the resource
*/
CacheEntry.prototype.free = function (byTTL) {
this.freedByTTL = byTTL || false;
if (this.cached) {
this.cached = false;
delete this.cache._inner[this.key];
}
};
/**
* Allocates the resource
* @returns {CacheEntry}
*/
CacheEntry.prototype.allocate = function () {
if (!this.cached) {
this.cache._inner[this.key] = this;
this.cached = true;
}
this.touch();
return this;
};
/**
* Sets the time to live
* @param {number} ticks TTL in ticks, 0 if not set
* @param {number} time TTL in seconds, 0 if not set
* @returns {CacheEntry}
*/
CacheEntry.prototype.setTimeToLive = function (ticks, seconds) {
this.ttlTicks = ticks || 0;
this.ttlSeconds = seconds || 0;
return this;
};
CacheEntry.prototype.isStillAlive = function () {
var cache = this.cache;
return ((this.ttlTicks == 0) || (this.touchTicks + this.ttlTicks < cache.updateTicks )) &&
((this.ttlSeconds == 0) || (this.touchSeconds + this.ttlSeconds < cache.updateSeconds ));
};
/**
* makes sure that resource wont freed by Time To Live
* if resource was already freed by TTL, put it in cache again
*/
CacheEntry.prototype.touch = function () {
var cache = this.cache;
if (this.cached) {
this.touchTicks = cache.updateTicks;
this.touchSeconds = cache.updateSeconds;
} else if (this.freedByTTL) {
this.freedByTTL = false;
if (!cache._inner[this.key]) {
cache._inner[this.key] = this;
}
}
};