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