forked from playcanvas/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathref-counted-cache.js
More file actions
44 lines (40 loc) · 1.3 KB
/
ref-counted-cache.js
File metadata and controls
44 lines (40 loc) · 1.3 KB
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
// Class implementing reference counting cache for objects
class RefCountedCache {
constructor() {
// The cache. The key is the object being stored in the cache.
// The value is ref count of the object. When that reaches zero,
// destroy function on the object gets called and object is removed
// from the cache.
this.cache = new Map();
}
// destroy all stored objects
destroy() {
this.cache.forEach((refCount, object) => {
object.destroy();
});
this.cache.clear();
}
// add object reference to the cache
incRef(object) {
const refCount = (this.cache.get(object) || 0) + 1;
this.cache.set(object, refCount);
}
// remove object reference from the cache
decRef(object) {
if (object) {
let refCount = this.cache.get(object);
if (refCount) {
refCount--;
if (refCount === 0) {
// destroy object and remove it from cache
this.cache.delete(object);
object.destroy();
} else {
// update new ref count in the cache
this.cache.set(object, refCount);
}
}
}
}
}
export { RefCountedCache };