Skip to content

Commit a794f67

Browse files
authored
Merge pull request #12 from keithamus/patch-1
allow for customising of the hash return type as `H`
2 parents 5c2f4a3 + e6355fb commit a794f67

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

index.ts

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

88
/**
99
* The Cache implementation to provide. Must be a Map or Map-alike.
1010
* Defaults to a Map. Useful for replacing the cache with an LRU cache or similar.
1111
*/
12-
cache?: Map<unknown, R>
12+
cache?: Map<H, R>
1313
}
1414

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

17-
export function defaultHash(...args: unknown[]): string {
17+
export function defaultHash<A extends unknown[], H extends unknown>(...args: A): H {
1818
// 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
2020
}
2121

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>(
2323
fn: MemoizableFunction<A, R, T>,
24-
opts: MemoizeOptions<A, R> = {}
24+
opts: MemoizeOptions<A, R, H> = {}
2525
): 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 {
2828
const id = hash.apply(this, args)
29-
if (cache.has(id)) return cache.get(id)
29+
if (cache.has(id)) return cache.get(id)!
3030
let result = fn.apply(this, args)
3131
if (result instanceof Promise) {
3232
// eslint-disable-next-line github/no-then

0 commit comments

Comments
 (0)