Add prototype TimedCache

This commit is contained in:
Herbert Wolverson
2024-12-02 15:26:36 -06:00
parent 126b8c172c
commit f2d6a20d2e

33
helpers/timed_cache.js Normal file
View File

@@ -0,0 +1,33 @@
// Keeps items for up to 10 seconds. Items are tagged by a key, which will
// be used to avoid duplicates.
export class TimedCache {
constructor(maxAge = 10) {
this.cache = new Map();
this.maxAge = maxAge;
}
addOrUpdate(key, value) {
this.cache.set(key, { value: value, age: 0 });
}
tick() {
let toRemove = [];
this.cache.forEach((val, key) => {
val.age += 1;
if (val.age > this.maxAge) {
toRemove.push(key);
}
});
toRemove.forEach((key) => {
this.cache.delete(key)
});
}
get() {
let result = [];
this.cache.forEach((val) => {
result.push(val.value);
})
return result;
}
}