Skip to content

Commit

Permalink
handle size calculation of background fetches, add test
Browse files Browse the repository at this point in the history
Re: #257
  • Loading branch information
isaacs committed Nov 2, 2022
1 parent ff254a7 commit f351e68
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions index.js
Expand Up @@ -379,6 +379,11 @@ class LRUCache {
this.sizes[index] = 0
}
this.requireSize = (k, v, size, sizeCalculation) => {
// provisionally accept background fetches.
// actual value size will be checked when they return.
if (this.isBackgroundFetch(v)) {
return 0
}
if (!isPosInt(size)) {
if (sizeCalculation) {
if (typeof sizeCalculation !== 'function') {
Expand Down Expand Up @@ -588,6 +593,9 @@ class LRUCache {
// if the item doesn't fit, don't do anything
// NB: maxEntrySize set to maxSize by default
if (this.maxEntrySize && size > this.maxEntrySize) {
// have to delete, in case a background fetch is there already.
// in non-async cases, this is a no-op
this.delete(k)
return this
}
let index = this.size === 0 ? undefined : this.keyMap.get(k)
Expand Down
16 changes: 16 additions & 0 deletions test/size-calculation.ts
Expand Up @@ -242,3 +242,19 @@ t.test('large item falls out of cache because maxEntrySize', t => {

t.end()
})

t.test('maxEntrySize, no maxSize', async t => {
const c = new LRU<number, string>({
max: 10,
maxEntrySize: 10,
sizeCalculation: s => s.length,
fetchMethod: async n => 'x'.repeat(n),
})
t.equal(await c.fetch(2), 'xx')
t.equal(c.size, 1)
t.equal(await c.fetch(3), 'xxx')
t.equal(c.size, 2)
t.equal(await c.fetch(11), 'x'.repeat(11))
t.equal(c.size, 2)
t.equal(c.has(11), false)
})

0 comments on commit f351e68

Please sign in to comment.