-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,34 @@ | ||
import memoize from 'fast-memoize' | ||
import fastMemoize, { Options } from 'fast-memoize' | ||
import { AnyFunction } from './isFunction' | ||
|
||
export { memoize } | ||
export interface MemoizeOptions<T extends AnyFunction = AnyFunction> { | ||
createCache?(): { | ||
set(key: string, value: any): void, | ||
get(key: string): any, | ||
has(key: string): boolean, | ||
}, | ||
serializer?(args: Parameters<T>): string, | ||
} | ||
|
||
/** | ||
* 函数参数结果缓存。 | ||
* | ||
* @param fn 要缓存的函数 | ||
* @param [options] 选项 | ||
* @returns 缓存化后的函数 | ||
*/ | ||
export function memoize<T extends AnyFunction>(fn: T, options?: MemoizeOptions<T>): T { | ||
let fastMemoizeOptions: Options<T> = undefined | ||
if (options) { | ||
fastMemoizeOptions = {} | ||
if (options.createCache) { | ||
fastMemoizeOptions.cache = { | ||
create: options.createCache, | ||
} as any | ||
} | ||
if (options.serializer) { | ||
fastMemoizeOptions.serializer = options.serializer as any | ||
} | ||
} | ||
return fastMemoize(fn, fastMemoizeOptions) | ||
} |