{"name":"tiny-lru","version":"13.1.0","keywords":["LRU","cache","caching","TTL","ttl-cache","least-recently-used","lightweight","fast","performance","memoization","expiration","typescript","nodejs","browser","esm","zero-dependencies"],"author":{"name":"Jason Mulligan","email":"jason.mulligan@avoidwork.com"},"license":"BSD-3-Clause","_id":"tiny-lru@13.1.0","maintainers":[{"name":"avoidwork","email":"jason.mulligan@avoidwork.com"}],"homepage":"https://github.com/avoidwork/tiny-lru","bugs":{"url":"https://github.com/avoidwork/tiny-lru/issues"},"dist":{"shasum":"649c3ee0bf441b30f7923397776a5dd5e8f17996","tarball":"http://registry-npm.ywwl.com/tiny-lru/download/tiny-lru-13.1.0.tgz","fileCount":6,"integrity":"sha512-sImTU4L5bvqNJxr95Jk6I/IZeHwTU6fWLfA6PuALDKnugw78YlGVkyDpPLzdzX02WU1zgrLIGSRJ8sLrtAJx5g==","signatures":[{"sig":"MEYCIQCoL0Mzn3c0cwz9Hb0toSDqZ+T1zxXv18fHm1v8n//PDwIhAJDsBGey0GqYzQe+dlnxXzQmZxHfZ4/mOEwK6n59giXo","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"sig":"MEYCIQCP4piXQNXnxKPI2hGT7rsjMRT98YcJpk4Kp7XGQCltgwIhAKaV+jxVE1AjVLpogIynNzbuj/B/0YgA7U3n6K4w7t6n","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":62330,"size":12309,"noattachment":false,"key":"/tiny-lru/-/tiny-lru-13.1.0.tgz"},"main":"dist/tiny-lru.cjs","type":"module","types":"types/lru.d.ts","source":"src/lru.js","engines":{"node":">=14"},"exports":{"types":"./types/lru.d.ts","import":"./dist/tiny-lru.js","require":"./dist/tiny-lru.cjs"},"gitHead":"657301ca34beda444990b8a85350f6c45d148efd","scripts":{"fix":"oxlint --fix *.js benchmarks src tests/unit && oxfmt *.js benchmarks src tests/unit --write","lint":"oxlint *.js benchmarks src tests/unit && oxfmt *.js benchmarks/*.js src/*.js tests/unit/*.js --check","test":"npm run lint && node --test tests/**/*.js","build":"npm run lint && npm run rollup","rollup":"rollup --config","prepare":"husky","coverage":"node --test --experimental-test-coverage --test-coverage-exclude=dist/** --test-coverage-exclude=tests/** --test-reporter=spec tests/**/*.test.js 2>&1 | grep -A 1000 \"start of coverage report\" > coverage.txt","changelog":"auto-changelog -p","benchmark:all":"npm run benchmark:modern && npm run benchmark:perf && npm run benchmark:comparison","benchmark:perf":"node benchmarks/performance-observer-benchmark.js","benchmark:modern":"node benchmarks/modern-benchmark.js","benchmark:comparison":"npm run benchmark:install-deps && node benchmarks/comparison-benchmark.js","benchmark:install-deps":"npm install --no-save lru-cache quick-lru mnemonist"},"_npmUser":{"name":"avoidwork","email":"jason.mulligan@avoidwork.com"},"repository":{"url":"git://github.com/avoidwork/tiny-lru.git","type":"git"},"_npmVersion":"11.11.0","description":"A fast, lightweight LRU (Least Recently Used) cache for JavaScript with O(1) operations and optional TTL support.","directories":{},"_nodeVersion":"25.8.1","engineStrict":true,"_hasShrinkwrap":false,"devDependencies":{"husky":"^9.1.7","oxfmt":"^0.57.0","oxlint":"^1.56.0","rollup":"^4.60.0","tinybench":"^6.0.0","auto-changelog":"^2.5.0","@rollup/plugin-terser":"^1.0.0"},"_npmOperationalInternal":{"tmp":"tmp/tiny-lru_13.1.0_1790477942694_0.4230387066665344","host":"s3://npm-registry-packages-npm-production"},"readme":"# Tiny LRU\n\n[![npm version](https://img.shields.io/npm/v/tiny-lru.svg)](https://www.npmjs.com/package/tiny-lru)\n[![npm downloads](https://img.shields.io/npm/dm/tiny-lru.svg)](https://www.npmjs.com/package/tiny-lru)\n[![License](https://img.shields.io/npm/l/tiny-lru.svg)](https://github.com/avoidwork/tiny-lru/blob/master/LICENSE)\n[![Node.js version](https://img.shields.io/node/v/tiny-lru.svg)](https://www.npmjs.com/package/tiny-lru)\n[![Build Status](https://github.com/avoidwork/tiny-lru/actions/workflows/ci.yml/badge.svg)](https://github.com/avoidwork/tiny-lru/actions?query=workflow%3Aci)\n[![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)](https://app.codecov.io/gh/avoidwork/tiny-lru)\n\nA high-performance, lightweight LRU (Least Recently Used) cache for JavaScript with O(1) operations and optional TTL support.\n\n## What is an LRU Cache?\n\nThink of an LRU cache like a limited-size bookshelf. When you add a new book and the shelf is full, you remove the **least recently used** book to make room. Every time you read a book, it moves to the front. This pattern is perfect for caching where you want to keep the most frequently accessed items.\n\nThe tiny-lru library provides:\n- **O(1)** operations for get, set, delete, and has\n- Optional **TTL (Time-To-Live)** support for automatic expiration\n- **Zero dependencies** - pure JavaScript\n- **100% test coverage** - fully tested and reliable\n- **TypeScript support** - full type definitions included\n- **~1.6 KB** minified and gzipped (compared to ~5.8 KB for lru-cache)\n\n## Installation\n\n```bash\nnpm install tiny-lru\n```\n\nRequires Node.js ≥14 or modern browsers with ES Module support.\n\n## Quick Start\n\n```javascript\nimport { lru } from \"tiny-lru\";\n\n// Create a cache that holds up to 100 items\nconst cache = lru(100);\n\n// Store and retrieve data\ncache.set(\"user:42\", { name: \"Alice\", score: 1500 });\nconst user = cache.get(\"user:42\"); // { name: \"Alice\", score: 1500 }\n\n// Chain operations\ncache.set(\"a\", 1).set(\"b\", 2).set(\"c\", 3);\n\n// Check what's in the cache\ncache.has(\"a\"); // true\ncache.size; // 3\ncache.keys(); // ['a', 'b', 'c'] (LRU order)\n```\n\n### TypeScript\n\n```typescript\nimport { LRU } from \"tiny-lru\";\n\ninterface User {\n  id: number;\n  name: string;\n}\n\nconst cache = new LRU<User>(100);\ncache.set(\"user:1\", { id: 1, name: \"Alice\" });\nconst user: User | undefined = cache.get(\"user:1\");\n```\n\n## With TTL (Time-to-Live)\n\nItems can automatically expire after a set time:\n\n```javascript\n// Cache that expires after 5 seconds\nconst sessionCache = lru(100, 5000);\n\nsessionCache.set(\"session:id\", { userId: 123 });\n// After 5 seconds, this returns undefined\nsessionCache.get(\"session:id\");\n```\n\nWant TTL to reset when you update an item? Enable `resetTtl`:\n\n```javascript\nconst cache = lru(100, 60000, true); // 1 minute TTL, resets on update\ncache.set(\"key\", \"value\");\ncache.set(\"key\", \"new value\"); // TTL resets\n```\n\n## When to Use Tiny LRU\n\n**Great for:**\n\n- API response caching\n- Function memoization\n- Session storage with expiration\n- Rate limiting\n- LLM response caching\n- Database query result caching\n- Any scenario where you want to limit memory usage\n\n**Not ideal for:**\n\n- Non-string keys (keys are coerced to strings, so objects and other non-primitives can collide)\n- Very large caches (consider a database)\n\n## API Reference\n\n### Factory Function: `lru(max?, ttl?, resetTtl?)`\n\nCreates a new LRU cache instance with parameter validation.\n\n```javascript\nimport { lru } from \"tiny-lru\";\n\nconst cache1 = lru(); // 1000 items, no TTL\nconst cache2 = lru(500); // 500 items, no TTL\nconst cache3 = lru(100, 30000); // 100 items, 30s TTL\nconst cache4 = lru(100, 60000, true); // with resetTtl enabled\n```\n\n**Parameters:**\n\n| Name       | Type      | Default | Description                                                      |\n| ---------- | --------- | ------- | ---------------------------------------------------------------- |\n| `max`      | `number`  | `1000`  | Maximum items. `0` = unlimited. Must be >= 0.                    |\n| `ttl`      | `number`  | `0`     | Time-to-live in milliseconds. `0` = no expiration. Must be >= 0. |\n| `resetTTL` | `boolean` | `false` | Reset TTL when updating existing items via `set()`               |\n\n**Returns:** `LRU` - New cache instance\n\n**Throws:** `TypeError` if parameters are invalid\n\n### Class: `new LRU(max?, ttl?, resetTtl?)`\n\nCreates an LRU cache instance with parameter validation.\n\n```javascript\nimport { LRU } from \"tiny-lru\";\n\nconst cache = new LRU(100, 5000);\n```\n\n**Parameters:**\n\n| Name       | Type      | Default | Description                                        |\n| ---------- | --------- | ------- | -------------------------------------------------- |\n| `max`      | `number`  | `0`     | Maximum items. `0` = unlimited.                    |\n| `ttl`      | `number`  | `0`     | Time-to-live in milliseconds. `0` = no expiration. |\n| `resetTTL` | `boolean` | `false` | Reset TTL when updating via `set()`                |\n\n### Properties\n\n| Property  | Type             | Description                                |\n| --------- | ---------------- | ------------------------------------------ |\n| `first`   | `object` \\| `null`  | Least recently used item (node with `key`, `value`, `prev`, `next`, `expiry`) |\n| `items`   | `object`         | Internal hash map of key → item nodes      |\n| `last`    | `object` \\| `null`  | Most recently used item (node with `key`, `value`, `prev`, `next`, `expiry`) |\n| `max`     | `number`         | Maximum items allowed                      |\n| `resetTTL`| `boolean`        | Whether TTL resets on `set()` updates      |\n| `size`    | `number`         | Current number of items                    |\n| `ttl`     | `number`         | Time-to-live in milliseconds               |\n\n### Methods\n\n| Method                      | Description                                    |\n| --------------------------- | ---------------------------------------------- |\n| `cleanup(fireOnEvict?)`     | Remove expired items without LRU update. Returns count of removed items. Pass `true` to fire `onEvict` for each removed item. |\n| `clear()`                   | Remove all items. Returns `this` for chaining. |\n| `delete(key)`               | Remove an item by key. Returns `this` for chaining. |\n| `entries(keys?)`            | Get `[key, value]` pairs. Without keys: LRU order. With keys: input array order. |\n| `evict()`                   | Remove the least recently used item. Returns `this` for chaining. |\n| `expiresAt(key)`            | Get expiration timestamp for a key. Returns `number | undefined`. |\n| `forEach(callback, thisArg?)` | Iterate over items in LRU order. Returns `this` for chaining. |\n| `get(key)`                  | Retrieve a value. Moves item to most recent. Returns value or `undefined`. |\n| `getMany(keys)`             | Batch retrieve multiple items. Returns object mapping keys to values (undefined for missing/expired keys). |\n| `has(key)`                  | Check if key exists and is not expired. Returns `boolean`. |\n| `hasAll(keys)`              | Check if ALL keys exist. Returns `boolean`.    |\n| `hasAny(keys)`              | Check if ANY key exists. Returns `boolean`.    |\n| `keys()`                    | Get all keys in LRU order (oldest first). Returns `any[]`. |\n| `keysByTTL()`               | Get keys by TTL status. Returns `{valid, expired, noTTL}`. |\n| `onEvict(callback)`         | Register eviction callback (triggers on `evict()` or when `set()` evicts). Returns `this` for chaining. |\n| `peek(key)`                 | Retrieve a value without LRU update or TTL check. Returns value or `undefined`. |\n| `set(key, value)`           | Store a value. Returns `this` for chaining.    |\n| `setWithEvicted(key, value)` | Store value, return evicted item if full. Returns `{key, value, expiry} | null`. |\n| `sizeByTTL()`               | Get counts by TTL status. Returns `{valid, expired, noTTL}`. |\n| `stats()`                   | Get cache statistics. Returns `{hits, misses, sets, deletes, evictions}`. |\n| `toJSON()`                  | Serialize cache to JSON format. Returns array of items. |\n| `values(keys?)`             | Get all values, or values for specific keys. Returns array of values. |\n| `valuesByTTL()`             | Get values by TTL status. Returns `{valid, expired, noTTL}`. |\n\n## Common Patterns\n\n### Memoization\n\n```javascript\nfunction memoize(fn, maxSize = 100) {\n  const cache = lru(maxSize);\n\n  return function (...args) {\n    const key = JSON.stringify(args);\n\n    if (cache.has(key)) {\n      return cache.get(key);\n    }\n\n    const result = fn(...args);\n    cache.set(key, result);\n    return result;\n  };\n}\n\n// Cache expensive computations\nconst fib = memoize((n) => (n <= 1 ? n : fib(n - 1) + fib(n - 2)), 50);\nfib(100); // fast - cached\nfib(100); // even faster - from cache\n```\n\n### Cache-Aside Pattern\n\n```javascript\n// Cache instance shared across calls (outside the function)\nconst cache = lru(1000, 60000); // 1 minute cache\n\nasync function getUser(userId) {\n  // Check cache first\n  const cached = cache.get(`user:${userId}`);\n  if (cached) {\n    return cached;\n  }\n\n  // Fetch from database\n  const user = await db.users.findById(userId);\n\n  // Store in cache\n  cache.set(`user:${userId}`, user);\n\n  return user;\n}\n```\n\n### Finding What Was Evicted\n\n```javascript\nconst cache = lru(3);\ncache.set(\"a\", 1).set(\"b\", 2).set(\"c\", 3);\n\nconst evicted = cache.setWithEvicted(\"d\", 4);\nconsole.log(evicted); // { key: 'a', value: 1, expiry: 0 }\n\ncache.keys(); // ['b', 'c', 'd']\n```\n\n## Advanced Usage\n\n### Batch Operations with Keys\n\n```javascript\nconst cache = lru(100);\ncache.set(\"users:1\", { name: \"Alice\" });\ncache.set(\"users:2\", { name: \"Bob\" });\ncache.set(\"users:3\", { name: \"Carol\" });\n\n// Get values for specific keys (order matches input array)\nconst values = cache.values([\"users:3\", \"users:1\"]);\n// ['Carol', 'Alice'] - matches input key order\n```\n\n### Interop with Lodash\n\n```javascript\nimport _ from \"lodash\";\nimport { lru } from \"tiny-lru\";\n\n_.memoize.Cache = lru().constructor;\n\nconst slowFunc = _.memoize(expensiveOperation);\nslowFunc.cache.max = 100; // Configure cache size\n```\n\n### Session and Authentication Caching\n\n```javascript\nimport { LRU } from \"tiny-lru\";\n\nclass AuthCache {\n  constructor() {\n    // Session cache: 30 minutes with TTL reset on update\n    this.sessions = new LRU(10000, 1800000, true);\n    // Token validation cache: 5 minutes, no reset\n    this.tokens = new LRU(5000, 300000, false);\n    // Permission cache: 15 minutes\n    this.permissions = new LRU(5000, 900000);\n  }\n\n  cacheSession(sessionId, userData, domain = \"app\") {\n    const key = `${domain}:session:${sessionId}`;\n    this.sessions.set(key, {\n      userId: userData.userId,\n      permissions: userData.permissions,\n      loginTime: Date.now(),\n      lastActivity: Date.now(),\n    });\n  }\n\n  getSession(sessionId, domain = \"app\") {\n    const key = `${domain}:session:${sessionId}`;\n    return this.sessions.get(key);\n  }\n}\n```\n\n### LLM Response Caching\n\n```javascript\nimport { LRU } from \"tiny-lru\";\n\nclass LLMCache {\n  constructor() {\n    // Cache up to 1000 responses for 1 hour\n    this.cache = new LRU(1000, 3600000); // 1 hour TTL\n  }\n\n  async getResponse(model, prompt, params = {}) {\n    const key = this.generateKey(model, prompt, params);\n\n    // Check cache first\n    const cached = this.cache.get(key);\n    if (cached) {\n      return { ...cached, fromCache: true };\n    }\n\n    // Make expensive API call\n    const response = await this.callLLMAPI(model, prompt, params);\n\n    // Cache the response\n    this.cache.set(key, {\n      response: response.text,\n      tokens: response.tokens,\n      timestamp: Date.now(),\n    });\n\n    return { ...response, fromCache: false };\n  }\n\n  generateKey(model, prompt, params = {}) {\n    const paramsHash = this.hashObject(params);\n    const promptHash = this.hashString(prompt);\n    return `llm:${model}:${promptHash}:${paramsHash}`;\n  }\n\n  hashString(str) {\n    let hash = 0;\n    for (let i = 0; i < str.length; i++) {\n      const char = str.charCodeAt(i);\n      hash = (hash << 5) - hash + char;\n      hash = hash & hash;\n    }\n    return Math.abs(hash).toString(36);\n  }\n\n  hashObject(obj) {\n    return this.hashString(JSON.stringify(obj, Object.keys(obj).sort()));\n  }\n}\n```\n\n## Why Tiny LRU?\n\nBundle sizes below are minified and gzipped, measured against the current releases.\n\n| Feature          | tiny-lru     | lru-cache   | quick-lru   |\n| ---------------- | ------------ | ----------- | ----------- |\n| Bundle size      | ~1.6 KB      | ~5.8 KB     | ~1.2 KB     |\n| O(1) operations  | ✅           | ✅          | ✅          |\n| TTL support      | ✅           | ✅          | ✅*          |\n| TypeScript       | ✅           | ✅          | ❌          |\n| Zero dependencies| ✅           | ✅          | ✅          |\n| Pure LRU         | ✅           | ✅          | ❌*          |\n\n\\* quick-lru uses a dual-cache design that can temporarily hold up to 2× the specified size, and its expiration is via `maxAge` rather than a `ttl` option.\n\n## Performance\n\nAll core operations are O(1):\n\n- **Set**: Add or update items\n- **Get**: Retrieve and promote to most recent\n- **Delete**: Remove items\n- **Has**: Quick existence check\n\n### Benchmarks\n\nRun our comprehensive benchmark suite to see performance characteristics:\n\n```bash\nnpm run benchmark:all\n```\n\nSee [benchmarks/README.md](https://github.com/avoidwork/tiny-lru/blob/master/benchmarks/README.md) for more details.\n\n## Development\n\n```bash\nnpm install           # Install dependencies\nnpm test             # Run lint and tests\nnpm run lint         # Lint and check formatting\nnpm run fix          # Fix lint and formatting issues\nnpm run build        # Build distribution files\nnpm run coverage     # Generate test coverage report\n```\n\n### Build Output\n\nBuild produces multiple module formats. When you install from npm, you'll get:\n- `dist/tiny-lru.js` - ES Modules\n- `dist/tiny-lru.cjs` - CommonJS\n- `types/lru.d.ts` - TypeScript definitions\n\nThe minified version (`dist/tiny-lru.min.js`) is available in the repository for local testing but is not shipped via npm.\n\n## Tests\n\n| Metric    | Count |\n| --------- | ----- |\n| Tests     | 169   |\n| Suites    | 27    |\n\n## Test Coverage\n\n| Metric    | Coverage |\n| --------- | -------- |\n| Lines     | 100%     |\n| Branches  | 99.39%   |\n| Functions | 100%     |\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Run `npm test` to ensure all tests pass\n4. Commit your changes (`git commit -m 'Add amazing feature'`)\n5. Push to the branch (`git push origin feature/amazing-feature`)\n6. Open a Pull Request\n\n## Security\n\ntiny-lru is a pure in-memory cache with no network or I/O surface. For guidance on key naming conventions that prevent cross-domain data leakage when using the cache, see the [Technical Documentation](https://github.com/avoidwork/tiny-lru/blob/master/docs/TECHNICAL_DOCUMENTATION.md).\n\n## Documentation\n\n- [API Reference](https://github.com/avoidwork/tiny-lru/blob/master/docs/API.md) - Complete API documentation\n- [Technical Documentation](https://github.com/avoidwork/tiny-lru/blob/master/docs/TECHNICAL_DOCUMENTATION.md) - Architecture, performance, and security\n- [Code Style Guide](https://github.com/avoidwork/tiny-lru/blob/master/docs/CODE_STYLE_GUIDE.md) - Contributing guidelines\n\n## License\n\nCopyright (c) 2026, Jason Mulligan\n\nBSD-3-Clause\n","publish_time":1790477942782,"_cnpm_publish_time":1790477942782,"dist-tags":{"latest":"13.1.1"}}