Skip to content

Commit

Permalink
fix: LRU cache not updating touched keys (#2693)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyscott18 authored Sep 5, 2024
1 parent 565bc6c commit 764f259
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-dancers-hear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"viem": patch
---

Fixed LRU algorithm to update touched keys.
17 changes: 17 additions & 0 deletions src/utils/lru.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
11 changes: 11 additions & 0 deletions src/utils/lru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ export class LruMap<value = unknown> extends Map<string, value> {
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)
Expand Down

0 comments on commit 764f259

Please sign in to comment.