From 48e179a75c20cd73b0e9d43c40c7f50d2085b90b Mon Sep 17 00:00:00 2001 From: Kyle Scott Date: Thu, 5 Sep 2024 15:54:46 -0400 Subject: [PATCH] Fix LRU cache not updating touched keys --- .changeset/dull-dancers-hear.md | 5 +++++ src/utils/lru.test.ts | 17 +++++++++++++++++ src/utils/lru.ts | 11 +++++++++++ 3 files changed, 33 insertions(+) create mode 100644 .changeset/dull-dancers-hear.md diff --git a/.changeset/dull-dancers-hear.md b/.changeset/dull-dancers-hear.md new file mode 100644 index 0000000000..7406c7800f --- /dev/null +++ b/.changeset/dull-dancers-hear.md @@ -0,0 +1,5 @@ +--- +"viem": patch +--- + +Fixed LRU algorithm to update touched keys. diff --git a/src/utils/lru.test.ts b/src/utils/lru.test.ts index 60fb159f27..2449644863 100644 --- a/src/utils/lru.test.ts +++ b/src/utils/lru.test.ts @@ -19,3 +19,20 @@ test('default', () => { expect(cache.get('f')).toBe(6) expect(cache.get('g')).toBe(7) }) + +test('update touched keys', () => { + const cache = new LruMap(5) + cache.set('a', 1) + cache.set('b', 2) + cache.set('c', 3) + cache.set('d', 4) + cache.set('e', 5) + expect(cache.size).toBe(5) + cache.get('a') + cache.set('f', 6) + cache.set('g', 7) + expect(cache.has('a')).toBe(true) + expect(cache.has('b')).toBe(false) + expect(cache.has('c')).toBe(false) + expect(cache.has('d')).toBe(true) +}) diff --git a/src/utils/lru.ts b/src/utils/lru.ts index 49c8151b80..193dc80d5c 100644 --- a/src/utils/lru.ts +++ b/src/utils/lru.ts @@ -11,6 +11,17 @@ export class LruMap extends Map { this.maxSize = size } + override get(key: string) { + const value = super.get(key) + + if (value !== undefined) { + this.delete(key) + super.set(key, value) + } + + return value + } + override set(key: string, value: value) { super.set(key, value) if (this.maxSize && this.size > this.maxSize)