|
| 1 | +import type { AnyFunction } from './types/common.js'; |
| 2 | + |
| 3 | +export type CacheKeyFn<Fn extends AnyFunction, ReturnValue = unknown> = (args: Parameters<Fn>) => ReturnValue; |
| 4 | + |
| 5 | +export type DefaultCacheKeyFn<Fn extends AnyFunction> = CacheKeyFn<Fn, NonNullable<Parameters<Fn>[0]> | string>; |
| 6 | + |
| 7 | +export type MemoizedFn<Fn extends AnyFunction, CkFn extends CacheKeyFn<Fn>> = Fn & { |
| 8 | + cache: Map<ReturnType<CkFn>, ReturnType<Fn>>; |
| 9 | +}; |
| 10 | + |
| 11 | +/** |
| 12 | + * Memoize a function |
| 13 | + * |
| 14 | + * @todo use `Map.getOrInsertComputed()` once it is widely available. |
| 15 | + */ |
| 16 | +export function memo<Fn extends AnyFunction, CkFn extends CacheKeyFn<Fn>>( |
| 17 | + fn: Fn, |
| 18 | + getCacheKey: CkFn, |
| 19 | +): MemoizedFn<Fn, CkFn>; |
| 20 | + |
| 21 | +export function memo<Fn extends AnyFunction>(fn: Fn): MemoizedFn<Fn, DefaultCacheKeyFn<Fn>>; |
| 22 | + |
| 23 | +export function memo<Fn extends AnyFunction, CkFn extends CacheKeyFn<Fn>>( |
| 24 | + fn: Fn, |
| 25 | + getCacheKey?: CkFn, |
| 26 | +): MemoizedFn<Fn, CkFn> { |
| 27 | + const defaultGetCacheKey: DefaultCacheKeyFn<Fn> = (args) => args[0] ?? JSON.stringify(args); |
| 28 | + |
| 29 | + const resolvedGetCacheKey = getCacheKey ?? defaultGetCacheKey; |
| 30 | + |
| 31 | + const memoized = (...args: Parameters<Fn>): ReturnType<Fn> => { |
| 32 | + const key = resolvedGetCacheKey(args); |
| 33 | + |
| 34 | + if (memoized.cache.has(key)) { |
| 35 | + return memoized.cache.get(key); |
| 36 | + } |
| 37 | + |
| 38 | + const value = fn(...args); |
| 39 | + |
| 40 | + memoized.cache.set(key, value); |
| 41 | + |
| 42 | + return value; |
| 43 | + }; |
| 44 | + |
| 45 | + memoized.cache = new Map(); |
| 46 | + |
| 47 | + return memoized as MemoizedFn<Fn, CkFn>; |
| 48 | +} |
0 commit comments