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

Add an internal function to refresh timer used for ttl #351

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 11 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

// module-private names and types
type Perf = { now: () => number }
const perf: Perf =
let perf: Perf =
typeof performance === 'object' &&
performance &&
typeof performance.now === 'function'
Expand Down Expand Up @@ -1259,6 +1259,7 @@ export class LRUCache<K extends {}, V extends {}, FC = unknown> {
c.#rindexes(options),
isStale: (index: number | undefined) =>
c.#isStale(index as Index),
refreshTTLTimerReference: () => c.#refreshTTLTimerReference(),
}
}

Expand Down Expand Up @@ -1557,6 +1558,15 @@ export class LRUCache<K extends {}, V extends {}, FC = unknown> {
}
}

#refreshTTLTimerReference() {
perf =
typeof performance === 'object' &&
performance &&
typeof performance.now === 'function'
? performance
: Date
}

// conditionally set private methods related to TTL
#updateItemAge: (index: Index) => void = () => {}
#statusTTL: (status: LRUCache.Status<V>, index: Index) => void =
Expand Down
35 changes: 35 additions & 0 deletions test/ttl-timer-refresh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
if (typeof performance === 'undefined') {
global.performance = require('perf_hooks').performance
}
import t from 'tap'
import { LRUCache } from '../dist/esm/index.js'
import { expose } from './fixtures/expose.js'

t.test('ttl timer refresh', async t => {
// @ts-ignore
global.performance = {
now: () => 5,
}
const { LRUCache: LRU } = t.mockRequire('../', {})
const c = new LRU({ max: 5, ttl: 10, ttlResolution: 0 })
const e = expose(c, LRU)

c.set('a', 1)

const status: LRUCache.Status<any> = {}
c.get('a', { status })
t.equal(status.now, 5)

// New timer mock
// @ts-ignore
global.performance = {
now: () => 10,
}

c.get('a', { status })
t.equal(status.now, 5, 'still using the old ttl timer')

e.refreshTTLTimerReference()
c.get('a', { status })
t.equal(status.now, 10, 'using the new ttl timer')
})