gitlify
Version:
A powerful CLI tool to analyze uncommitted git changes with detailed reports, function detection, and beautiful terminal output
115 lines (93 loc) • 2.41 kB
JavaScript
const config = require('../config.js');
class Cache {
constructor() {
this.cache = new Map();
this.ttl = config.cacheTTL;
this.maxSize = 1000; // Maximum number of cached items
}
set(key, value) {
// Check cache size limit
if (this.cache.size >= this.maxSize) {
this.evictOldest();
}
this.cache.set(key, {
value,
timestamp: Date.now()
});
}
get(key) {
const item = this.cache.get(key);
if (!item) return null;
// Check if item has expired
if (Date.now() - item.timestamp > this.ttl) {
this.cache.delete(key);
return null;
}
return item.value;
}
has(key) {
return this.cache.has(key) && !this.isExpired(key);
}
delete(key) {
return this.cache.delete(key);
}
clear() {
this.cache.clear();
}
isExpired(key) {
const item = this.cache.get(key);
if (!item) return true;
return Date.now() - item.timestamp > this.ttl;
}
evictOldest() {
let oldestKey = null;
let oldestTime = Date.now();
for (const [key, item] of this.cache.entries()) {
if (item.timestamp < oldestTime) {
oldestTime = item.timestamp;
oldestKey = key;
}
}
if (oldestKey) {
this.cache.delete(oldestKey);
}
}
// Clean up expired items
cleanup() {
for (const [key] of this.cache.entries()) {
if (this.isExpired(key)) {
this.cache.delete(key);
}
}
}
// Get cache statistics
getStats() {
const now = Date.now();
let expiredCount = 0;
let validCount = 0;
for (const [key, item] of this.cache.entries()) {
if (now - item.timestamp > this.ttl) {
expiredCount++;
} else {
validCount++;
}
}
return {
total: this.cache.size,
valid: validCount,
expired: expiredCount,
hitRate: this.calculateHitRate()
};
}
// Simple hit rate calculation (would need to be implemented with hit tracking)
calculateHitRate() {
return 0; // Placeholder - would need hit/miss tracking
}
}
// Singleton cache instance
const cache = new Cache();
// Periodic cleanup
setInterval(() => {
cache.cleanup();
}, 60000); // Clean up every minute
module.exports = cache;