TTL Set

1.0.0 · active · verified Sun Apr 19

The `ttl-set` package provides a JavaScript `Set`-like data structure where each entry automatically expires after a specified time-to-live (TTL). It is currently at version 1.0.0, indicating a stable API with a well-defined feature set. The library's release cadence is likely infrequent due to its focused and stable utility functionality, serving as a robust solution for simple, time-bound caching needs. Its primary differentiator is the direct integration of TTL expiration into the `Set` interface, distinguishing it from general-purpose `Set` objects or more complex caching libraries that might offer LRU/LFU policies. This makes it ideal for scenarios requiring a basic, memory-efficient, and self-cleaning collection of unique values, such as tracking active sessions, recently seen items, or implementing basic rate-limiting without external dependencies or elaborate configuration. The core API mirrors `Set.prototype`, offering `add`, `has`, `clear`, and `size`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `TTLSet`, add elements, and observe their automatic expiration over time based on the defined TTL.

const TTLSet = require('ttl-set');

// Create a new TTLSet instance with a 1-minute (60,000 ms) time-to-live
const cache = new TTLSet(60 * 1000);

console.log('Adding "hello" to cache...');
cache.add('hello');

// Simulate waiting 40 seconds
setTimeout(() => {
  console.log('Adding "world" to cache after 40s...');
  cache.add('world');
  // "hello" is still alive (40s elapsed < 60s TTL)
  console.log('Has "hello" (40s)?', cache.has('hello')); // true
  console.log('Current cache size:', cache.size); // 2

  // Simulate waiting another 40 seconds (total 80s)
  setTimeout(() => {
    console.log('Checking cache after another 40s (total 80s)...');
    // "hello" should have expired (80s > 60s TTL)
    console.log('Has "hello" (80s)?', cache.has('hello')); // false
    // "world" should still be alive (40s elapsed for "world" < 60s TTL)
    console.log('Has "world" (40s for "world")?', cache.has('world')); // true
    console.log('Current cache size:', cache.size); // 1

    // Simulate waiting another 40 seconds (total 120s)
    setTimeout(() => {
      console.log('Checking cache after another 40s (total 120s)...');
      // "world" should now have expired (80s elapsed for "world" > 60s TTL)
      console.log('Has "world" (80s for "world")?', cache.has('world')); // false
      console.log('Current cache size:', cache.size); // 0
    }, 40 * 1000);

  }, 40 * 1000);

}, 40 * 1000);

view raw JSON →