Skip to content

Commit f7e6128

Browse files
authored
allow for customising of the hash return type as H
1 parent 5c2f4a3 commit f7e6128

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

index.ts

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,33 @@
1-
export interface MemoizeOptions<A extends unknown[], R> {
1+
2+
export interface MemoizeOptions<A extends unknown[], R, H = unknown> {
23
/**
34
* Provides a single value to use as the Key for the memoization.
45
* Defaults to `JSON.stringify` (ish).
56
*/
6-
hash?: (...args: A) => unknown
7+
hash?: (...args: A) => H
78

89
/**
910
* The Cache implementation to provide. Must be a Map or Map-alike.
1011
* Defaults to a Map. Useful for replacing the cache with an LRU cache or similar.
1112
*/
12-
cache?: Map<unknown, R>
13+
cache?: Map<H, R>
1314
}
1415

1516
export type MemoizableFunction<A extends unknown[], R extends unknown, T extends unknown> = (this: T, ...args: A) => R
1617

17-
export function defaultHash(...args: unknown[]): string {
18+
export function defaultHash<A extends unknown[], H extends unknown>(...args: A): H {
1819
// 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+
return JSON.stringify(args, (_: unknown, v: unknown) => (typeof v === 'object' ? v : String(v))) as H
2021
}
2122

22-
export default function memoize<A extends unknown[], R extends unknown, T extends unknown>(
23+
export default function memoize<A extends unknown[], R extends unknown, T extends unknown, H extends unknown>(
2324
fn: MemoizableFunction<A, R, T>,
24-
opts: MemoizeOptions<A, R> = {}
25+
opts: MemoizeOptions<A, R, H> = {}
2526
): MemoizableFunction<A, R, T> {
26-
const {hash = defaultHash, cache = new Map()} = opts
27-
return function (this: T, ...args: A) {
27+
const {hash = defaultHash, cache = new Map<H, R>()} = opts
28+
return function (this: T, ...args: A): R {
2829
const id = hash.apply(this, args)
29-
if (cache.has(id)) return cache.get(id)
30+
if (cache.has(id)) return cache.get(id)!
3031
let result = fn.apply(this, args)
3132
if (result instanceof Promise) {
3233
// eslint-disable-next-line github/no-then

0 commit comments

Comments
 (0)