@croct/cache
Version:
An abstraction layer for caching.
53 lines (52 loc) • 1.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.LruCache = void 0;
/**
* In-memory Least Recently Used (LRU) cache.
*/
class LruCache {
constructor(capacity) {
this.cache = new Map();
this.capacity = capacity;
}
/**
* Initializes a new instance with the given capacity.
*
* @param {number} capacity The maximum number of entries in the cache. Must be a
* positive safe integer.
*/
static ofCapacity(capacity) {
if (!Number.isSafeInteger(capacity) || capacity < 1) {
throw new Error('LRU capacity must be a positive safe integer.');
}
return new this(capacity);
}
get(key, loader) {
if (!this.cache.has(key)) {
return loader(key);
}
const value = this.cache.get(key);
// Reposition the key as the most recently used value
this.cache.delete(key);
this.cache.set(key, value);
return Promise.resolve(value);
}
set(key, value) {
this.cache.set(key, value);
this.prune();
return Promise.resolve();
}
delete(key) {
this.cache.delete(key);
return Promise.resolve();
}
prune() {
while (this.cache.size > this.capacity) {
const leastRecentlyUsedKey = this.cache
.keys()
.next();
this.cache.delete(leastRecentlyUsedKey.value);
}
}
}
exports.LruCache = LruCache;