Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 1x 1x 3x 3x 3x 25x 9x 9x 9x 9x 3x 3x 3x 3x 6x 2x 2x 2x 4x 9x 3x | import { exactEqual } from './utils'
// TODO@wendellhu: this type is not deal well
export type CacheKeyFn<U> = (...args: any[]) => string
export function memoizeFunc<T extends (...args: any[]) => any>(
fn: T,
cacheKeyFn?: CacheKeyFn<Parameters<T>>
): T {
let hasRun = false
let newParams: Parameters<T>
const cachedLastValue = new Map<string, ReturnType<T>>()
const cachedLastParams = new Map<string, Parameters<T>>()
const wrapped = function(...args: Parameters<T>) {
const key = cacheKeyFn?.(...args) || 'only'
newParams = args
const lastParams = cachedLastParams.get(key) || []
let lastValue
if (!hasRun) {
hasRun = true
lastValue = fn(...args)
cachedLastParams.set(key, newParams)
cachedLastValue.set(key, lastValue!)
} else if (!exactEqual(lastParams, newParams)) {
lastValue = fn(...args)
cachedLastParams.set(key, newParams)
cachedLastValue.set(key, lastValue!)
} else {
lastValue = cachedLastValue.get(key)!
}
return lastValue
}
return wrapped as T
}
|