Skip to content

Instantly share code, notes, and snippets.

@ThePratikSah
Created April 4, 2025 18:42
Show Gist options
  • Save ThePratikSah/99575e4131ceaf0cc1e020c9c5ced474 to your computer and use it in GitHub Desktop.
Save ThePratikSah/99575e4131ceaf0cc1e020c9c5ced474 to your computer and use it in GitHub Desktop.
class NanoCache {
constructor({ cleanupInterval = 5 * 60 * 60 * 1000 } = {}) { // Default cleanup every 5 hours
this.cache = new Map();
this.startCleanupInterval(cleanupInterval);
}
/**
* Set a key-value pair with optional TTL
* @param {string} key - The key to store
* @param {string} value - The value to store
* @param {number} ttl - Time to live in seconds (optional)
*/
set(key, value, ttl = null) {
if (typeof ttl !== 'number' || ttl <= 0) {
throw new Error('TTL must be a positive number of seconds');
}
const item = {
value,
timestamp: Date.now(),
ttl: ttl ? ttl * 1000 : null // Convert to milliseconds
};
this.cache.set(key, item);
}
/**
* Get a value by key
* @param {string} key - The key to retrieve
* @returns {string|null} The value or null if not found or expired
*/
get(key) {
const item = this.cache.get(key);
if (!item) return null;
if (item.ttl && Date.now() - item.timestamp > item.ttl) {
this.delete(key);
return null;
}
return item.value;
}
/**
* Delete a key from the cache
* @param {string} key - The key to delete
* @returns {boolean} True if the key was deleted, false if it didn't exist
*/
delete(key) {
return this.cache.delete(key);
}
/**
* Start the automatic cleanup interval
* @private
* @param {number} interval - Cleanup interval in milliseconds
*/
startCleanupInterval(interval) {
this.cleanupInterval = setInterval(() => {
const now = Date.now();
for (const [key, item] of this.cache.entries()) {
if (item.ttl && now - item.timestamp > item.ttl) {
this.delete(key);
}
}
}, interval);
}
/**
* Stop the automatic cleanup interval
*/
stopCleanup() {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval);
this.cleanupInterval = null;
}
}
}
module.exports = { NanoCache };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment