npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@philiprehberger/timeout-map

v0.3.0

Published

Map with automatic entry expiration — TTL per key

Readme

@philiprehberger/timeout-map

CI npm version Last updated

Map with automatic entry expiration — TTL per key

Installation

npm install @philiprehberger/timeout-map

Usage

import { TimeoutMap } from '@philiprehberger/timeout-map';

const cache = new TimeoutMap<string, string>();
cache.set('token', 'abc123', 60_000); // expires in 1 minute
cache.get('token'); // 'abc123'

Default TTL and Expiration Callback

import { TimeoutMap } from '@philiprehberger/timeout-map';

const map = new TimeoutMap<string, number>({
  defaultTtl: 5_000,
  onExpire: (key, value) => {
    console.log(`Expired: ${key} = ${value}`);
  },
});

map.set('a', 1); // uses defaultTtl

Sliding Window TTL

Extend an entry's TTL each time it is accessed via get() or has():

import { TimeoutMap } from '@philiprehberger/timeout-map';

const sessions = new TimeoutMap<string, object>({
  defaultTtl: 15 * 60_000, // 15 minutes
  slidingExpiration: true,
});

sessions.set('user:1', { role: 'admin' });
sessions.get('user:1'); // TTL reset to 15 minutes from now

Max Size Limit

Cap the number of entries and evict the oldest when the limit is exceeded:

import { TimeoutMap } from '@philiprehberger/timeout-map';

const cache = new TimeoutMap<string, Buffer>({
  maxSize: 1000,
  onEvict: (key) => {
    console.log(`Evicted: ${key}`);
  },
});

cache.set('key-1001', Buffer.from('data'));

Batch Operations

Efficiently set, get, or delete multiple entries at once:

import { TimeoutMap } from '@philiprehberger/timeout-map';

const map = new TimeoutMap<string, number>({ defaultTtl: 60_000 });

map.setMany([
  ['a', 1],
  ['b', 2],
  ['c', 3, 30_000], // per-key TTL override
]);

const results = map.getMany(['a', 'b', 'missing']);
// Map { 'a' => 1, 'b' => 2 }

const removed = map.deleteMany(['a', 'c']);
// 2

Periodic Background Cleanup

Eagerly remove expired entries on a timer instead of waiting for lazy access:

import { TimeoutMap } from '@philiprehberger/timeout-map';

const cache = new TimeoutMap<string, string>({
  defaultTtl: 60_000,
  onExpire: (key) => console.log(`Cleaned up: ${key}`),
});

cache.startCleanup(10_000); // sweep every 10 seconds
cache.stopCleanup();

Inspecting Entry Expiry

Get a value alongside its absolute expiry timestamp and remaining time:

import { TimeoutMap } from '@philiprehberger/timeout-map';

const cache = new TimeoutMap<string, string>();
cache.set('token', 'abc123', 60_000);

const info = cache.getWithExpiry('token');
if (info) {
  console.log(info.value);       // 'abc123'
  console.log(info.expiresAt);   // ms-since-epoch timestamp
  console.log(info.remainingMs); // ~60000 immediately after set
}

Entries without a TTL report expiresAt and remainingMs as Infinity. Expired or missing keys return undefined.

Hit/Miss Statistics

Track cache effectiveness with built-in counters:

import { TimeoutMap } from '@philiprehberger/timeout-map';

const cache = new TimeoutMap<string, number>({ defaultTtl: 60_000 });
cache.set('a', 1);

cache.get('a');       // hit
cache.get('missing'); // miss

const stats = cache.stats();
// { size: 1, hits: 1, misses: 1, expirations: 0, hitRate: 0.5 }

cache.resetStats(); // zero counters for the next observation window

stats().expirations increments whenever a TTL-expired entry is removed — whether on lazy access, during [Symbol.iterator]/size, or via startCleanup().

API

new TimeoutMap<K, V>(options?)

| Option | Type | Default | Description | |--------|------|---------|-------------| | defaultTtl | number | undefined | Default TTL in milliseconds for all entries | | onExpire | (key, value) => void | undefined | Callback fired when an entry expires | | slidingExpiration | boolean | false | Reset TTL on each get() / has() access | | maxSize | number | undefined | Maximum number of entries; oldest evicted when exceeded | | onEvict | (key, value) => void | undefined | Callback fired when an entry is evicted due to maxSize |

Methods

| Method | Description | |--------|-------------| | set(key, value, ttl?) | Set a value with optional per-key TTL (overrides default) | | get(key) | Get a value, or undefined if expired or missing | | getWithExpiry(key) | Get { value, expiresAt, remainingMs }, or undefined if expired/missing | | has(key) | Check if a non-expired entry exists | | delete(key) | Remove an entry | | clear() | Remove all entries | | size | Count of non-expired entries (triggers cleanup) | | stats() | Returns { size, hits, misses, expirations, hitRate } | | resetStats() | Zero the hit/miss/expiration counters | | setMany(entries) | Set multiple [key, value, ttl?] tuples at once | | getMany(keys) | Get multiple values; returns a Map (omits missing/expired) | | deleteMany(keys) | Delete multiple keys; returns count of entries removed | | startCleanup(intervalMs) | Start periodic background expiration sweep | | stopCleanup() | Stop the background cleanup timer | | [Symbol.iterator]() | Iterate over non-expired [key, value] pairs |

Development

npm install
npm run build
npm test

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT