This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+41
View File
@@ -0,0 +1,41 @@
class Cache extends Map {
constructor(opts={}) {
super();
if (typeof opts === 'number') {
opts = { max:opts };
}
let { max, maxAge } = opts;
this.max = max > 0 && max || Infinity;
this.maxAge = maxAge !== void 0 ? maxAge : -1;
this.stale = !!opts.stale;
}
peek(key) {
return this.get(key, false);
}
set(key, content, maxAge = this.maxAge) {
this.has(key) && this.delete(key);
(this.size + 1 > this.max) && this.delete(this.keys().next().value);
let expires = maxAge > -1 && (maxAge + Date.now());
return super.set(key, { expires, content });
}
get(key, mut=true) {
let x = super.get(key);
if (x === void 0) return x;
let { expires, content } = x;
if (expires !== false && Date.now() >= expires) {
this.delete(key);
return this.stale ? content : void 0;
}
if (mut) this.set(key, content);
return content;
}
}
module.exports = Cache;