From 4804c4e5b127b5a998086a816d5b9798fe4b7650 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20P=C3=A5lsson?= Date: Wed, 28 Aug 2024 18:25:31 +0200 Subject: [PATCH] Add an internal function to refresh timer used for ttl When overriding the global timers with a custom timer, the timer used for ttl is not updated and will continue to use the timer that was defined when the package was first imported. This adds an internal function that can be called to refresh the timer used for ttl with the current global timer. --- src/index.ts | 12 +++++++++++- test/ttl-timer-refresh.ts | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 test/ttl-timer-refresh.ts diff --git a/src/index.ts b/src/index.ts index 20b833c..da7c55a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' @@ -1261,6 +1261,7 @@ export class LRUCache c.#rindexes(options), isStale: (index: number | undefined) => c.#isStale(index as Index), + refreshTTLTimerReference: () => c.#refreshTTLTimerReference(), } } @@ -1559,6 +1560,15 @@ export class LRUCache } } + #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, index: Index) => void = diff --git a/test/ttl-timer-refresh.ts b/test/ttl-timer-refresh.ts new file mode 100644 index 0000000..41ec3b2 --- /dev/null +++ b/test/ttl-timer-refresh.ts @@ -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 = {} + 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') +})