From 533e0094a17399e856e2bedc2ab20f26bbf8c6fc Mon Sep 17 00:00:00 2001 From: Joachim Viide Date: Sat, 6 Jul 2024 23:17:35 +0000 Subject: [PATCH] fix(lru): don't clear an already cached key on set --- internal/lrucache.js | 4 ++-- test/internal/lrucache.js | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/internal/lrucache.js b/internal/lrucache.js index 6d89ec94..7216e48e 100644 --- a/internal/lrucache.js +++ b/internal/lrucache.js @@ -21,9 +21,9 @@ class LRUCache { } set (key, value) { - const deleted = this.delete(key) + this.delete(key) - if (!deleted && value !== undefined) { + if (value !== undefined) { // If cache is full, delete the least recently used item if (this.map.size >= this.max) { const firstKey = this.map.keys().next().value diff --git a/test/internal/lrucache.js b/test/internal/lrucache.js index 83a0e797..0e2cb3d8 100644 --- a/test/internal/lrucache.js +++ b/test/internal/lrucache.js @@ -17,3 +17,25 @@ test('basic cache operation', t => { c.set(42, undefined) t.end() }) + +test('test setting the same key twice', t => { + const c = new LRUCache() + c.set(1, 1) + c.set(1, 2) + t.equal(c.get(1), 2) + t.end() +}) + +test('test that setting an already cached key bumps it last in the LRU queue', t => { + const c = new LRUCache() + const max = 1000 + + for (let i = 0; i < max; i++) { + c.set(i, i) + } + c.set(0, 0) + c.set(1001, 1001) + t.equal(c.get(0), 0) + t.equal(c.get(1), undefined) + t.end() +})