confinode
Version:
Node application configuration reader
70 lines • 1.71 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const QuickLRU = require("quick-lru");
/**
* A LRU cache with a timeout.
*/
class Cache {
/**
* The cache constructor.
*
* @param maxAge - The maximum amount of time in milliseconds the cache is kept alive while unused.
* @param capacity - The maximum amount of objects kept in cache.
*/
constructor(maxAge, capacity) {
this.maxAge = maxAge;
this.lru = new QuickLRU({ maxSize: capacity });
}
/**
* Set the item.
*
* @param key - The key of the item.
* @param value - The item to cache.
*/
set(key, value) {
this.resetTimer();
this.lru.set(key, value);
}
/**
* Test if the key is in the cache.
*
* @param key - The key to test.
* @returns True if the key is in the cache.
*/
has(key) {
this.resetTimer();
return this.lru.has(key);
}
/**
* Retrieve the cached item.
*
* @param key - The key of the item to retrieve.
* @returns The cached item.
*/
get(key) {
this.resetTimer();
return this.lru.get(key);
}
/**
* Clear the content of the cache.
*/
clear() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = undefined;
}
this.lru.clear();
}
/**
* Clean the stale objects.
*/
resetTimer() {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => this.clear(), this.maxAge);
this.timer.unref();
}
}
exports.default = Cache;
//# sourceMappingURL=Cache.js.map