|
| 1 | +export interface MemoizeOptions<A extends unknown[], R> { |
| 2 | + /** |
| 3 | + * Provides a single value to use as the Key for the memoization. |
| 4 | + * Defaults to `JSON.stringify` (ish). |
| 5 | + */ |
| 6 | + hash?: (...args: A) => unknown |
| 7 | + |
| 8 | + /** |
| 9 | + * The Cache implementation to provide. Must be a Map or Map-alike. |
| 10 | + * Defaults to a Map. Useful for replacing the cache with an LRU cache or similar. |
| 11 | + */ |
| 12 | + cache?: Map<unknown, R> |
| 13 | +} |
| 14 | + |
| 15 | +export type MemoizableFunction<A extends unknown[], R extends unknown, T extends unknown> = (this: T, ...args: A) => R |
| 16 | + |
| 17 | +export function defaultHash(...args: unknown[]): string { |
| 18 | + // JSON.stringify ellides `undefined` and function values by default. We do not want that. |
| 19 | + return JSON.stringify(args, (_: unknown, v: unknown) => (typeof v === 'object' ? v : String(v))) |
| 20 | +} |
| 21 | + |
| 22 | +export default function memoize<A extends unknown[], R extends unknown, T extends unknown>( |
| 23 | + fn: MemoizableFunction<A, R, T>, |
| 24 | + opts: MemoizeOptions<A, R> = {} |
| 25 | +): MemoizableFunction<A, R, T> { |
| 26 | + const {hash = defaultHash, cache = new Map()} = opts |
| 27 | + return function (this: T, ...args: A) { |
| 28 | + const id = hash.apply(this, args) |
| 29 | + if (cache.has(id)) return cache.get(id) |
| 30 | + const result = fn.apply(this, args) |
| 31 | + if (result instanceof Promise) { |
| 32 | + // eslint-disable-next-line github/no-then |
| 33 | + result.catch(error => { |
| 34 | + cache.delete(id) |
| 35 | + throw error |
| 36 | + }) |
| 37 | + } |
| 38 | + cache.set(id, result) |
| 39 | + return result |
| 40 | + } |
| 41 | +} |
0 commit comments