generated from templates/typescript-library
add invalidate() method
This commit is contained in:
parent
6c21f00f6d
commit
ddbda71a84
14
src/async.ts
14
src/async.ts
@ -75,6 +75,10 @@ export interface MemoAsyncStoredResult<T extends AsyncFunc> {
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
export type MemoizedAsyncFunc<T extends AsyncFunc> = T & {
|
||||
invalidate(...params: Params<T>) : void;
|
||||
};
|
||||
|
||||
export function memo_async<T extends AsyncFunc>(opts: MemoAsyncOptions<T>) : T {
|
||||
const get_key = opts.key ?? default_key;
|
||||
const storage: Record<string, MemoAsyncStoredResult<T>> = Object.create(null);
|
||||
@ -230,7 +234,15 @@ export function memo_async<T extends AsyncFunc>(opts: MemoAsyncOptions<T>) : T {
|
||||
}
|
||||
}
|
||||
|
||||
return memoized as unknown as T;
|
||||
memoized.invalidate = function invalidate(...params: Params<T>) {
|
||||
const key = get_key(params);
|
||||
|
||||
if (storage[key]) {
|
||||
evict(storage[key]);
|
||||
}
|
||||
};
|
||||
|
||||
return memoized as unknown as MemoizedAsyncFunc<T>;
|
||||
}
|
||||
|
||||
function default_key(...params: any[]) : string {
|
||||
|
18
src/full.ts
18
src/full.ts
@ -54,7 +54,11 @@ export interface MemoStoredResult<T extends Func> {
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
export function memo<T extends Func>(opts: MemoOptions<T>) : T {
|
||||
export type MemoizedFunc<T extends Func> = T & {
|
||||
invalidate(...params: Params<T>) : void;
|
||||
};
|
||||
|
||||
export function memo<T extends Func>(opts: MemoOptions<T>) : MemoizedFunc<T> {
|
||||
const get_key = opts.key ?? default_key;
|
||||
const storage: Record<string, MemoStoredResult<T>> = Object.create(null);
|
||||
|
||||
@ -76,6 +80,11 @@ export function memo<T extends Func>(opts: MemoOptions<T>) : T {
|
||||
const evicted = storage[key];
|
||||
delete storage[key];
|
||||
|
||||
if (evicted.timer) {
|
||||
clearTimeout(evicted.timer);
|
||||
evicted.timer = null;
|
||||
}
|
||||
|
||||
if (opts.on_evict) {
|
||||
opts.on_evict(evicted);
|
||||
}
|
||||
@ -100,7 +109,12 @@ export function memo<T extends Func>(opts: MemoOptions<T>) : T {
|
||||
record.timer = setTimeout(() => evict(record.key), ttl);
|
||||
}
|
||||
|
||||
return memoized as unknown as T;
|
||||
memoized.invalidate = function invalidate(...params: Params<T>) {
|
||||
const key = get_key(params);
|
||||
evict(key);
|
||||
};
|
||||
|
||||
return memoized as unknown as MemoizedFunc<T>;
|
||||
}
|
||||
|
||||
function default_key(...params: any[]) : string {
|
||||
|
Loading…
x
Reference in New Issue
Block a user