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
2 changes: 1 addition & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function memoize<A extends unknown[], R extends unknown, T extend
if (result instanceof Promise) {
// eslint-disable-next-line github/no-then
result = result.catch(error => {
cache.delete(id)
if (cache.get(id) === result) cache.delete(id)
throw error
}) as R
}
Expand Down
18 changes: 18 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,24 @@ describe('memoize', () => {
})

describe('cache option', () => {
it('keeps a replacement cache entry when an evicted promise rejects', async () => {
const cache = new Map<string, Promise<string>>()
let rejectFirst!: (reason: Error) => void
const first = new Promise<string>((_, reject) => {
rejectFirst = reject
})
const callback = vi.fn().mockReturnValueOnce(first).mockResolvedValue('replacement')
const memo = memoize(callback, {cache, hash: () => 'key'})
const pending = memo()
cache.delete('key')
const replacement = memo()
rejectFirst(new Error('evicted request failed'))
await expect(pending).rejects.toThrow('evicted request failed')
expect(memo()).toBe(replacement)
expect(await replacement).toBe('replacement')
expect(callback).toHaveBeenCalledTimes(2)
})

it('uses `has`/`get`/`set` on the Cache implementation', () => {
const cache = new Map()
const hasSpy = vi.spyOn(cache, 'has')
Expand Down