add invalidate() method
All checks were successful
Build and test / build-and-test (18.x) (push) Successful in 13s
Build and test / build-and-test (20.x) (push) Successful in 12s

This commit is contained in:
James Brumond 2023-08-26 16:09:57 -07:00
parent 6c21f00f6d
commit ddbda71a84
Signed by: james
GPG Key ID: E8F2FC44BAA3357A
2 changed files with 29 additions and 3 deletions

View File

@ -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 {

View File

@ -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);
}
@ -99,8 +108,13 @@ export function memo<T extends Func>(opts: MemoOptions<T>) : T {
record.expires = record.created + ttl;
record.timer = setTimeout(() => evict(record.key), ttl);
}
memoized.invalidate = function invalidate(...params: Params<T>) {
const key = get_key(params);
evict(key);
};
return memoized as unknown as T;
return memoized as unknown as MemoizedFunc<T>;
}
function default_key(...params: any[]) : string {