From ddbda71a840070a6a1f9474b0409fc9a82077946 Mon Sep 17 00:00:00 2001 From: James Brumond Date: Sat, 26 Aug 2023 16:09:57 -0700 Subject: [PATCH] add invalidate() method --- src/async.ts | 14 +++++++++++++- src/full.ts | 18 ++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/async.ts b/src/async.ts index d67df9c..075aa68 100644 --- a/src/async.ts +++ b/src/async.ts @@ -75,6 +75,10 @@ export interface MemoAsyncStoredResult { timer: ReturnType; } +export type MemoizedAsyncFunc = T & { + invalidate(...params: Params) : void; +}; + export function memo_async(opts: MemoAsyncOptions) : T { const get_key = opts.key ?? default_key; const storage: Record> = Object.create(null); @@ -230,7 +234,15 @@ export function memo_async(opts: MemoAsyncOptions) : T { } } - return memoized as unknown as T; + memoized.invalidate = function invalidate(...params: Params) { + const key = get_key(params); + + if (storage[key]) { + evict(storage[key]); + } + }; + + return memoized as unknown as MemoizedAsyncFunc; } function default_key(...params: any[]) : string { diff --git a/src/full.ts b/src/full.ts index f97df30..65760b8 100644 --- a/src/full.ts +++ b/src/full.ts @@ -54,7 +54,11 @@ export interface MemoStoredResult { timer: ReturnType; } -export function memo(opts: MemoOptions) : T { +export type MemoizedFunc = T & { + invalidate(...params: Params) : void; +}; + +export function memo(opts: MemoOptions) : MemoizedFunc { const get_key = opts.key ?? default_key; const storage: Record> = Object.create(null); @@ -76,6 +80,11 @@ export function memo(opts: MemoOptions) : 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(opts: MemoOptions) : T { record.expires = record.created + ttl; record.timer = setTimeout(() => evict(record.key), ttl); } + + memoized.invalidate = function invalidate(...params: Params) { + const key = get_key(params); + evict(key); + }; - return memoized as unknown as T; + return memoized as unknown as MemoizedFunc; } function default_key(...params: any[]) : string {