@modern-js/runtime-utils
Version:
A Progressive React Framework for modern web development.
45 lines (44 loc) • 1.11 kB
JavaScript
import { LRUCache } from "lru-cache";
class MemoryContainer {
async get(key) {
return this.cache.get(key);
}
async set(key, value) {
this.cache.set(key, value);
return this;
}
async has(key) {
return this.cache.has(key);
}
async delete(key) {
const exist = await this.has(key);
if (exist) {
this.cache.delete(key);
}
return exist;
}
forEach(callbackFn) {
this.cache.forEach((value, key) => {
callbackFn(value, key, this);
});
}
constructor({ max, maxAge } = {}) {
this.cache = new LRUCache({
maxSize: (max || 256) * MemoryContainer.MB,
ttl: maxAge || MemoryContainer.hour,
sizeCalculation: (value, key) => {
return JSON.stringify(value).length;
}
});
}
}
MemoryContainer.BYTE = 1;
MemoryContainer.KB = 1024 * MemoryContainer.BYTE;
MemoryContainer.MB = 1024 * MemoryContainer.KB;
MemoryContainer.ms = 1;
MemoryContainer.second = MemoryContainer.ms * 1e3;
MemoryContainer.minute = MemoryContainer.second * 60;
MemoryContainer.hour = MemoryContainer.minute * 60;
export {
MemoryContainer
};