Skip to content

Commit

Permalink
Add noUpdateTTL option to set without updating TTL
Browse files Browse the repository at this point in the history
Fix: #104
  • Loading branch information
isaacs committed Feb 22, 2022
1 parent 9c05bcd commit ddc6344
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ class LRUCache {
dispose,
disposeAfter,
noDisposeOnSet,
noUpdateTTL,
maxSize,
sizeCalculation,
} = options
Expand Down Expand Up @@ -134,6 +135,7 @@ class LRUCache {
this.disposed = null
}
this.noDisposeOnSet = !!noDisposeOnSet
this.noUpdateTTL = !!noUpdateTTL

if (this.maxSize) {
if (!isPosInt(this.maxSize)) {
Expand Down Expand Up @@ -357,6 +359,7 @@ class LRUCache {
noDisposeOnSet = this.noDisposeOnSet,
size = 0,
sizeCalculation = this.sizeCalculation,
noUpdateTTL = this.noUpdateTTL,
} = {}) {
let index = this.size === 0 ? undefined : this.keyMap.get(k)
if (index === undefined) {
Expand All @@ -370,6 +373,7 @@ class LRUCache {
this.tail = index
this.size ++
this.addItemSize(index, v, k, size, sizeCalculation)
noUpdateTTL = false
} else {
// update
const oldVal = this.valList[index]
Expand All @@ -389,7 +393,9 @@ class LRUCache {
if (ttl !== 0 && this.ttl === 0 && !this.ttls) {
this.initializeTTLTracking()
}
this.setItemTTL(index, ttl)
if (!noUpdateTTL) {
this.setItemTTL(index, ttl)
}
if (this.disposeAfter) {
while (this.disposed.length) {
this.disposeAfter(...this.disposed.shift())
Expand Down
25 changes: 25 additions & 0 deletions test/ttl.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,31 @@ const runTests = (LRU, t) => {
t.end()
})

t.test('no update ttl', t => {
const c = new LRU({ max: 10, ttlResolution: 0, noUpdateTTL: true, ttl: 10 })
for (let i = 0; i < 3; i++) {
c.set(i, i)
}
clock.advance(9)
// set, but do not update ttl. this will fall out.
c.set(0, 0)

// set, but update the TTL
c.set(1, 1, { noUpdateTTL: false })
clock.advance(9)
c.purgeStale()

t.equal(c.get(2), undefined, 'fell out of cache normally')
t.equal(c.get(1), 1, 'still in cache, ttl updated')
t.equal(c.get(0), undefined, 'fell out of cache, despite update')

clock.advance(9)
c.purgeStale()
t.equal(c.get(1), undefined, 'fell out of cache after ttl update')

t.end()
})

t.end()
}

Expand Down

0 comments on commit ddc6344

Please sign in to comment.