class CacheManager {
constructor(maxSize = 100, defaultTTL = 60000) {
this.cache = new Map();
this.maxSize = maxSize;
this.defaultTTL = defaultTTL;
this.timers = new Map();
}
set(key, value, ttl = this.defaultTTL) {
if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
const firstKey = this.cache.keys().next().value;
this.delete(firstKey);
}
this.delete(key);
this.cache.set(key, value);
if (ttl > 0) {
const timer = setTimeout(() => this.delete(key), ttl);
this.timers.set(key, timer);
}
}
get(key) {
return this.cache.get(key);
}
delete(key) {
const timer = this.timers.get(key);
if (timer) {
clearTimeout(timer);
this.timers.delete(key);
}
return this.cache.delete(key);
}
clear() {
this.timers.forEach(timer => clearTimeout(timer));
this.timers.clear();
this.cache.clear();
}
size() {
return this.cache.size;
}
}
module.exports = CacheManager;