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
37 changes: 0 additions & 37 deletions src/lru.js
Original file line number Diff line number Diff line change
Expand Up @@ -580,10 +580,6 @@ export class LRU {
x = next;
}

if (removed > 0) {
this.#rebuildList();
}

return removed;
}

Expand Down Expand Up @@ -706,39 +702,6 @@ export class LRU {

return { valid, expired, noTTL: [] };
}

/**
* Rebuild the doubly-linked list after cleanup by deleting expired items.
* This removes nodes that were deleted during cleanup.
*
* @private
*/
#rebuildList() {
if (this.size === 0) {
this.first = null;
this.last = null;
return;
}

const keys = this.keys();
this.first = null;
this.last = null;

for (let i = 0; i < keys.length; i++) {
const item = this.items[keys[i]];
if (item !== null && item !== undefined) {
if (this.first === null) {
this.first = item;
item.prev = null;
} else {
item.prev = this.last;
this.last.next = item;
}
item.next = null;
this.last = item;
}
}
}
}

/**
Expand Down
16 changes: 16 additions & 0 deletions tests/unit/lru.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,22 @@ describe("LRU Cache", function () {
cache = new LRU(5, 100);
});

it("should keep the list intact when an item expires during cleanup", function (t) {
const times = [0, 50, 100, 149, 150];
let index = 0;
t.mock.method(Date, "now", () => times[index++] ?? 150);
cache.set("a", 1);
cache.set("b", 2);

assert.equal(cache.cleanup(), 1);
assert.equal(cache.size, 1);
assert.equal(cache.first, cache.items.b);
assert.equal(cache.last, cache.items.b);
assert.doesNotThrow(() => cache.evict());
assert.equal(cache.size, 0);
assert.deepEqual(Object.keys(cache.items), []);
});

it("should remove expired items", async function () {
cache.set("a", 1);
cache.set("b", 2);
Expand Down
Loading