Cache for web server in Typescript
🧩 Syntax:
class Cache<T> {
private items: Map<string, { value: T; expiration: number }>;
private ttl: number;
constructor(ttl: number) {
this.items = new Map();
this.ttl = ttl;
}
// Add an item to the cache
set(key: string, value: T): void {
const expiration = Date.now() + this.ttl;
this.items.set(key, { value, expiration });
// Auto-remove expired items
setTimeout(() => {
if (this.items.has(key) && this.items.get(key)!.expiration <= Date.now()) {
this.items.delete(key);
}
}, this.ttl);
}
// Retrieve an item from the cache
get(key: string): T | undefined {
const item = this.items.get(key);
if (!item || item.expiration <= Date.now()) {
this.items.delete(key);
return undefined;
}
return item.value;
}
// Remove an item
delete(key: string): void {
this.items.delete(key);
}
// Check if the cache contains a key
has(key: string): boolean {
return this.items.has(key);
}
}
// Example usage
const cache = new Cache<string>(5000); // TTL: 5 seconds
cache.set("key1", "value1");
setTimeout(() => {
const value = cache.get("key1");
console.log(value ? `Value: ${value}` : "Key not found or expired");
}, 3000);
setTimeout(() => {
const value = cache.get("key1");
console.log(value ? `Value: ${value}` : "Key not found or expired");
}, 6000);