UNPKG

jsonblade

Version:

A powerful and modular JSON template engine with extensible filters

77 lines 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.templateCache = void 0; exports.getCachedTemplate = getCachedTemplate; exports.setCachedTemplate = setCachedTemplate; exports.clearTemplateCache = clearTemplateCache; exports.getTemplateStats = getTemplateStats; class TemplateCache { constructor(maxSize = 100, ttl = 5 * 60 * 1000) { this.cache = new Map(); // 5 minutes default TTL this.maxSize = maxSize; this.ttl = ttl; } get(template) { const entry = this.cache.get(template); if (!entry) return undefined; // Check if entry is expired if (Date.now() - entry.lastUsed > this.ttl) { this.cache.delete(template); return undefined; } // Update last used time and use count entry.lastUsed = Date.now(); entry.useCount++; return entry; } set(template, compiledFunction) { // Remove least recently used entries if cache is full if (this.cache.size >= this.maxSize) { this.evictLRU(); } this.cache.set(template, { compiledFunction, lastUsed: Date.now(), useCount: 1, }); } clear() { this.cache.clear(); } getStats() { const totalUses = Array.from(this.cache.values()).reduce((sum, entry) => sum + entry.useCount, 0); return { size: this.cache.size, maxSize: this.maxSize, hitRate: totalUses > 0 ? this.cache.size / totalUses : 0, }; } evictLRU() { let oldestEntry = null; for (const entry of this.cache.entries()) { if (!oldestEntry || entry[1].lastUsed < oldestEntry[1].lastUsed) { oldestEntry = entry; } } if (oldestEntry) { this.cache.delete(oldestEntry[0]); } } } exports.templateCache = new TemplateCache(); function getCachedTemplate(template) { const entry = exports.templateCache.get(template); return entry?.compiledFunction; } function setCachedTemplate(template, compiledFunction) { exports.templateCache.set(template, compiledFunction); } function clearTemplateCache() { exports.templateCache.clear(); } function getTemplateStats() { return exports.templateCache.getStats(); } //# sourceMappingURL=template-cache.js.map