Cache Manager

In-memory cache with TTL support and automatic expiration

javascript (ES2020) 2025-11-12 cache ttl memory storage

Description

A simple in-memory cache implementation with time-to-live (TTL) support. Automatically expires entries after a specified duration.

Features

  • TTL-based expiration
  • Automatic cleanup
  • Size limits
  • Get/set/delete operations

Code

RAW
class CacheManager {  constructor(maxSize = 100, defaultTTL = 60000) {    this.cache = new Map();    this.maxSize = maxSize;    this.defaultTTL = defaultTTL;    this.timers = new Map();  }    set(key, value, ttl = this.defaultTTL) {    if (this.cache.size >= this.maxSize && !this.cache.has(key)) {      const firstKey = this.cache.keys().next().value;      this.delete(firstKey);    }        this.delete(key);    this.cache.set(key, value);        if (ttl > 0) {      const timer = setTimeout(() => this.delete(key), ttl);      this.timers.set(key, timer);    }  }    get(key) {    return this.cache.get(key);  }    delete(key) {    const timer = this.timers.get(key);    if (timer) {      clearTimeout(timer);      this.timers.delete(key);    }    return this.cache.delete(key);  }    clear() {    this.timers.forEach(timer => clearTimeout(timer));    this.timers.clear();    this.cache.clear();  }    size() {    return this.cache.size;  }}module.exports = CacheManager;
RAW
const CacheManager = require('./cache');const cache = new CacheManager(100, 60000);cache.set('user:123', { id: 123, name: 'John Doe' }, 5000);const user = cache.get('user:123');console.log('Cached user:', user);setTimeout(() => {  console.log('After TTL:', cache.get('user:123'));}, 5000 + 100);

Comments

No comments yet. Be the first to comment!