Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,15 @@ const cache = new LRU(100, 5000);

| Method | Description |
| --------------------------- | ---------------------------------------------- |
| `cleanup()` | Remove expired items without LRU update. Returns count of removed items. |
| `cleanup(fireOnEvict?)` | Remove expired items without LRU update. Returns count of removed items. Pass `true` to fire `onEvict` for each removed item. |
| `clear()` | Remove all items. Returns `this` for chaining. |
| `delete(key)` | Remove an item by key. Returns `this` for chaining. |
| `entries(keys?)` | Get `[key, value]` pairs. Without keys: LRU order. With keys: input array order. |
| `evict()` | Remove the least recently used item. Returns `this` for chaining. |
| `expiresAt(key)` | Get expiration timestamp for a key. Returns `number | undefined`. |
| `forEach(callback, thisArg?)` | Iterate over items in LRU order. Returns `this` for chaining. |
| `get(key)` | Retrieve a value. Moves item to most recent. Returns value or `undefined`. |
| `getMany(keys)` | Batch retrieve multiple items. Returns object mapping keys to values (missing/expired keys omitted). |
| `getMany(keys)` | Batch retrieve multiple items. Returns object mapping keys to values (undefined for missing/expired keys). |
| `has(key)` | Check if key exists and is not expired. Returns `boolean`. |
| `hasAll(keys)` | Check if ALL keys exist. Returns `boolean`. |
| `hasAny(keys)` | Check if ANY key exists. Returns `boolean`. |
Expand Down
4 changes: 2 additions & 2 deletions coverage.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
ℹ file | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ src | | | |
ℹ lru.js | 100.00 | 99.39 | 100.00 |
ℹ lru.js | 100.00 | 99.40 | 100.00 |
ℹ ----------------------------------------------------------
ℹ all files | 100.00 | 99.39 | 100.00 |
ℹ all files | 100.00 | 99.40 | 100.00 |
ℹ ----------------------------------------------------------
ℹ end of coverage report
11 changes: 10 additions & 1 deletion docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,15 +163,24 @@ console.log(cache.ttl); // 60000

### `cleanup()`

Removes expired items without affecting LRU order. Silently removes expired items without triggering the `onEvict()` callback.
Removes expired items without affecting LRU order. By default it silently removes expired items without triggering the `onEvict()` callback. Pass `true` to fire `onEvict()` for each removed item.

```javascript
cache.set("a", 1).set("b", 2);
// ... wait for items to expire
const removed = cache.cleanup();
console.log(removed); // 2 (number of items removed)

// Fire onEvict for each purged item
const removedWithCallback = cache.cleanup(true);
```

**Parameters:**

| Name | Type | Default | Description |
| -------------- | --------- | ------- | ------------------------------------------------ |
| `fireOnEvict` | `boolean` | `false` | When `true`, invokes `onEvict()` for each removed item. |

**Returns:** `number` - Number of expired items removed

**Note:** Only removes items when TTL is enabled (`ttl > 0`). Does not support method chaining (returns `number`).
Expand Down
23 changes: 15 additions & 8 deletions src/lru.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,17 +312,16 @@ export class LRU {

/**
* Returns an array of all keys in the cache, ordered from least to most recently used.
* Expired items are skipped, consistent with entries(), values(), and toJSON().
*
* @returns {string[]} Array of keys in LRU order.
*/
keys() {
const result = Array.from({ length: this.size });
let x = this.first;
let i = 0;

while (x !== null) {
result[i++] = x.key;
x = x.next;
const result = [];
for (let x = this.first; x !== null; x = x.next) {
if (!this.#isExpired(x)) {
result.push(x.key);
}
}

return result;
Expand Down Expand Up @@ -548,9 +547,10 @@ export class LRU {
* Remove expired items without affecting LRU order.
* Unlike get(), this does not move items to the end.
*
* @param {boolean} [fireOnEvict=false] - When true, invokes the onEvict callback for each removed item.
* @returns {number} Number of expired items removed.
*/
cleanup() {
cleanup(fireOnEvict = false) {
if (this.ttl === 0 || this.size === 0) {
return 0;
}
Expand All @@ -568,6 +568,13 @@ export class LRU {
this.#unlink(x);
x.prev = null;
x.next = null;
if (fireOnEvict && this.#onEvict !== null) {
this.#onEvict({
key: x.key,
value: x.value,
expiry: x.expiry,
});
}
}
}
x = next;
Expand Down
38 changes: 38 additions & 0 deletions tests/unit/lru.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,36 @@ describe("LRU Cache", function () {
const removed = cache.cleanup();
assert.equal(removed, 0);
});

it("should fire onEvict for each removed item when fireOnEvict is true", async function () {
cache.set("a", 1);
cache.set("b", 2);

await new Promise((resolve) => setTimeout(resolve, 150));

const evicted = [];
cache.onEvict((item) => evicted.push(item.key));

const removed = cache.cleanup(true);
assert.equal(removed, 2);
assert.equal(cache.size, 0);
assert.deepEqual(evicted, ["a", "b"]);
});

it("should not fire onEvict when fireOnEvict is false (default)", async function () {
cache.set("a", 1);
cache.set("b", 2);

await new Promise((resolve) => setTimeout(resolve, 150));

const evicted = [];
cache.onEvict((item) => evicted.push(item.key));

const removed = cache.cleanup();
assert.equal(removed, 2);
assert.equal(cache.size, 0);
assert.deepEqual(evicted, []);
});
});

describe("toJSON method", function () {
Expand Down Expand Up @@ -1661,6 +1691,14 @@ describe("LRU Cache", function () {
assert.deepEqual(cache.values(), []);
});

it("should skip expired items in keys()", async function () {
const cache = new LRU(5, 50, false);
cache.set("a", 1);
cache.set("b", 2);
await new Promise((resolve) => setTimeout(resolve, 80));
assert.deepEqual(cache.keys(), []);
});

it("should skip expired items in entries()", async function () {
const cache = new LRU(5, 50, false);
cache.set("a", 1);
Expand Down
3 changes: 2 additions & 1 deletion types/lru.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,10 @@ export class LRU<T = any> {
/**
* Remove expired items without affecting LRU order.
* Unlike get(), this does not move items to the end.
* @param fireOnEvict When true, invokes the onEvict callback for each removed item
* @returns Number of expired items removed
*/
cleanup(): number;
cleanup(fireOnEvict?: boolean): number;

/**
* Serialize cache to JSON-compatible format.
Expand Down
Loading