From 789bdec16c6810dff30dbc5860a8489ba643ec9a Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Fri, 17 Nov 2023 12:50:53 -0500 Subject: [PATCH] Accept any CommonCache instance as optional cache option. --- src/index.ts | 13 ++++--------- src/tests/api.ts | 9 +++------ 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/src/index.ts b/src/index.ts index c8ec07a..915d1b3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -90,9 +90,6 @@ export type OptimisticWrapperFunction< }; export { CommonCache } -export interface CommonCacheConstructor { - new >(max?: number, dispose?: (value: V, key?: K) => void): CommonCache; -} export type OptimisticWrapOptions< TArgs extends any[], @@ -113,7 +110,7 @@ export type OptimisticWrapOptions< // If provided, the subscribe function should either return an unsubscribe // function or return nothing. subscribe?: (...args: TArgs) => void | (() => any); - Cache?: CommonCacheConstructor, NoInfer, NoInfer> + cache?: CommonCache, Entry, NoInfer>>; }; const caches = new Set>(); @@ -128,13 +125,11 @@ export function wrap< makeCacheKey = (defaultMakeCacheKey as () => TCacheKey), keyArgs, subscribe, - Cache = StrongCache -}: OptimisticWrapOptions = Object.create(null)) { - const cache = new Cache>( + cache = new StrongCache( max, entry => entry.dispose(), - ); - + ), +}: OptimisticWrapOptions = Object.create(null)) { const optimistic = function (): TResult { const key = makeCacheKey.apply( null, diff --git a/src/tests/api.ts b/src/tests/api.ts index cb1366f..6cafa99 100644 --- a/src/tests/api.ts +++ b/src/tests/api.ts @@ -38,13 +38,8 @@ describe("optimism", function () { }); it("can manually set the `Cache` implementation", () => { - let cache!: Cache; - class Cache implements CommonCache { private _cache = new Map() - constructor() { - cache = this; - } has = this._cache.has.bind(this._cache); get = this._cache.get.bind(this._cache); delete = this._cache.delete.bind(this._cache); @@ -56,13 +51,15 @@ describe("optimism", function () { clean(){}; } + const cache = new Cache(); + const wrapped = wrap( (obj: { value: string }) => obj.value + " transformed", { + cache, makeCacheKey(obj) { return obj.value; }, - Cache, } ); assert.ok(cache instanceof Cache);