diginext-utils
Version:
README.md
119 lines (118 loc) • 4.14 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const formatBytes_1 = __importDefault(require("../string/formatBytes"));
class CacheManager {
constructor(props) {
this.MAX_CACHE_SIZE = 1000;
this.cache = new Map();
this.MAX_CACHE_SIZE = (props === null || props === void 0 ? void 0 : props.maxCacheSize) || 1000;
}
get(id, updateLastAccessed = true) {
try {
const entry = this.cache.get(id);
if (entry) {
const { lastAccessed, maxAge } = entry;
if (Date.now() - lastAccessed > maxAge) {
this.cache.delete(id);
return undefined;
}
if (updateLastAccessed)
entry.lastAccessed = Date.now(); // Update last accessed time
return entry.value;
}
}
catch (error) {
throw new Error(`Access Cache failed: ${error instanceof Error ? error.message : "Unknown error"}`);
}
return undefined;
}
add(id, value, maxAge = Number.MAX_VALUE) {
try {
this.evictEntryOutdate();
this.cache.set(id, {
value,
lastAccessed: Date.now(),
maxAge,
});
}
catch (error) {
throw new Error(`Add To Cache failed: ${error instanceof Error ? error.message : "Unknown error"}`);
}
}
evictEntryOutdate() {
const oldestId = this.evictMaxAgeEntry();
if (this.cache.size >= this.MAX_CACHE_SIZE && oldestId) {
this.cache.delete(oldestId);
}
}
evictMaxAgeEntry() {
const now = Date.now();
//
let oldestId = null;
let oldestAccess = Number.MAX_VALUE;
for (const [key, entry] of this.cache.entries()) {
if (entry.maxAge != Number.MAX_VALUE && now - entry.lastAccessed > entry.maxAge) {
this.cache.delete(key);
}
else {
if (entry.lastAccessed < oldestAccess) {
oldestAccess = entry.lastAccessed;
oldestId = key;
}
}
}
return oldestId;
}
update(id, value) {
try {
const now = Date.now();
const entry = this.cache.get(id);
if (entry) {
Object.assign(entry, value);
entry.lastAccessed = now;
this.cache.set(id, entry);
}
}
catch (error) {
throw new Error(`Update Cache failed: ${error instanceof Error ? error.message : "Unknown error"}`);
}
}
// Function to get rough size of the Map
getRoughSize() {
let size = 0;
this.cache.forEach((value, key) => {
size += this.getRoughSizeOfObject(key);
size += this.getRoughSizeOfObject(value);
});
return (0, formatBytes_1.default)(size);
}
// Helper function to get rough size of an object
getRoughSizeOfObject(object) {
const objectList = new Set();
const stack = [object];
let bytes = 0;
while (stack.length) {
const value = stack.pop();
if (typeof value === "boolean") {
bytes += 4;
}
else if (typeof value === "string") {
bytes += value.length * 2;
}
else if (typeof value === "number") {
bytes += 8;
}
else if (typeof value === "object" && value !== null && !objectList.has(value)) {
objectList.add(value);
for (const i in value) {
stack.push(value[i]);
}
}
}
return bytes;
}
}
exports.default = CacheManager;