Skip to content
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
9 changes: 5 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2113,17 +2113,18 @@ export class LRUCache<K extends {}, V extends {}, FC = unknown> {
load(arr: [K, LRUCache.Entry<V>][]) {
this.clear()
for (const [key, entry] of arr) {
if (entry.start) {
const options = { ...entry }
if (options.start) {
// entry.start is a portable timestamp, but we may be using
// node's performance.now(), so calculate the offset, so that
// we get the intended remaining TTL, no matter how long it's
// been on ice.
//
// it's ok for this to be a bit slow, it's a rare operation.
const age = Date.now() - entry.start
entry.start = this.#perf.now() - age
const age = Date.now() - options.start
options.start = this.#perf.now() - age
}
this.#set(key, entry.value, entry)
this.#set(key, entry.value, options)
}
}

Expand Down
21 changes: 21 additions & 0 deletions test/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,24 @@ const d = new LRU(c)
d.load(c.dump())

t.strictSame(d, c)

t.test('loading TTL entries does not mutate the reusable dump', t => {
const source = new LRU<string, string>({ max: 5, ttl: 60_000 })
source.set('key', 'value')
const entries = source.dump()
const snapshot = structuredClone(entries)
const first = new LRU<string, string>({ max: 5 })
const second = new LRU<string, string>({ max: 5 })

first.load(entries)
t.strictSame(
entries,
snapshot,
'preserves portable timestamps in the input',
)
second.load(entries)
t.equal(first.get('key'), 'value')
t.equal(second.get('key'), 'value')
t.ok(second.getRemainingTTL('key') > 0)
t.end()
})