Cache Class with Automatic Cleanup
This guide demonstrates how to use an updated Cache
class in your Node.js or TypeScript projects. The class includes a Time-to-Live (TTL) mechanism for cache entries, automatic cleanup of expired items, and a method to stop the cleanup process when needed.
Copy the following code into a file (e.g., Cache.ts
):
export class Cache<T> {
private store: Map<string, { timestamp: number; value: T }>;
private ttl: number;
private cleanupInterval: NodeJS.Timeout;
/**
* @param ttl Time to live in milliseconds.
* @param cleanupIntervalMs How frequently to run cleanup (optional, default 1 minute).
*/
constructor(ttl: number, cleanupIntervalMs: number = 60000) {
this.store = new Map();
this.ttl = ttl;
this.cleanupInterval = setInterval(() => this.cleanup(), cleanupIntervalMs);
}
get(key: string): T | null {
const cached = this.store.get(key);
if (!cached) return null;
if (Date.now() - cached.timestamp >= this.ttl) {
this.store.delete(key);
return null;
}
return cached.value;
}
set(key: string, value: T): void {
this.store.set(key, { timestamp: Date.now(), value });
}
delete(key: string): void {
this.store.delete(key);
}
clear(): void {
this.store.clear();
}
private cleanup() {
const now = Date.now();
for (const [key, { timestamp }] of this.store.entries()) {
if (now - timestamp >= this.ttl) {
this.store.delete(key);
}
}
}
// Optionally, add a method to stop cleanup if needed.
stopCleanup() {
clearInterval(this.cleanupInterval);
}
}
In another file (e.g., app.ts
), import the class and create an instance. In this example, we set up a cache with a TTL of 5 seconds (5000 milliseconds) and let the cleanup run every minute:
import { Cache } from './Cache';
const myCache = new Cache<string>(5000); // Cache that holds strings with a TTL of 5000ms
Use the set
method to store a value with a specific key:
myCache.set('greeting', 'Hello, world!');
console.log('Value set in cache.');
Use the get
method to retrieve a value. If the TTL has expired or the key doesn’t exist, it returns null
:
const greeting = myCache.get('greeting');
if (greeting) {
console.log('Cached value:', greeting);
} else {
console.log('Cache miss or expired.');
}
Remove a specific entry using the delete
method:
myCache.delete('greeting');
console.log('Value deleted from cache.');
To remove all entries, use the clear
method:
myCache.clear();
console.log('All cache cleared.');
If you need to stop the automatic cleanup (for example, before shutting down your application), use the stopCleanup
method:
myCache.stopCleanup();
console.log('Automatic cleanup stopped.');
Below is a complete example combining all of the steps above:
import { Cache } from './Cache';
// Create a cache with a 5-second TTL and cleanup running every minute
const myCache = new Cache<string>(5000);
// Set a value
myCache.set('greeting', 'Hello, world!');
console.log('Value set in cache.');
// Retrieve the value immediately
let greeting = myCache.get('greeting');
console.log('Immediately retrieved:', greeting);
// Wait for 6 seconds to let the value expire
setTimeout(() => {
greeting = myCache.get('greeting');
if (greeting) {
console.log('After timeout, cached value:', greeting);
} else {
console.log('After timeout, cache miss or expired.');
}
// Optionally, stop the cleanup interval
myCache.stopCleanup();
console.log('Automatic cleanup stopped.');
}, 6000);
- Import the Cache: Include the updated
Cache
class in your project. - Instantiate the Cache: Create an instance with a defined TTL and optional cleanup interval.
- Set and Get Data: Use
set
to cache data andget
to retrieve it. - Manage Cache: Use
delete
for individual keys,clear
to empty the cache, andstopCleanup
to halt the automatic cleanup process.
Happy coding!