zappyzep/src/SimpleCache.ts

61 lines
1.1 KiB
TypeScript
Raw Normal View History

2019-08-18 16:40:15 +03:00
import Timeout = NodeJS.Timeout;
const CLEAN_INTERVAL = 1000;
export class SimpleCache {
protected readonly retentionTime;
protected cleanTimeout: Timeout;
protected unloaded: boolean;
protected store: Map<string, { remove_at: number; value: any }>;
constructor(retentionTime) {
this.retentionTime = retentionTime;
this.store = new Map();
}
unload() {
this.unloaded = true;
clearTimeout(this.cleanTimeout);
}
cleanLoop() {
const now = Date.now();
for (const [key, info] of this.store.entries()) {
if (now >= info.remove_at) {
this.store.delete(key);
}
}
if (!this.unloaded) {
this.cleanTimeout = setTimeout(() => this.cleanLoop(), CLEAN_INTERVAL);
}
}
set(key: string, value) {
this.store.set(key, {
remove_at: Date.now() + this.retentionTime,
value,
});
}
get(key: string) {
const info = this.store.get(key);
if (!info) return null;
return info.value;
}
has(key: string) {
return this.store.has(key);
}
delete(key: string) {
this.store.delete(key);
}
clear() {
this.store.clear();
}
}