Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix LRU cache not updating touched keys #2693

Merged
merged 1 commit into from
Sep 5, 2024
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
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) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

curious if this should use super.has(key) instead to account for LruMap<undefined>?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah probably better

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