Skip to content

Commit

Permalink
Accept any CommonCache instance as optional cache option.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Nov 17, 2023
1 parent f57dec5 commit 789bdec
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 15 deletions.
13 changes: 4 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,6 @@ export type OptimisticWrapperFunction<
};

export { CommonCache }
export interface CommonCacheConstructor<TCacheKey, TResult, TArgs extends any[]> {
new <K extends TCacheKey, V extends Entry<TArgs, TResult>>(max?: number, dispose?: (value: V, key?: K) => void): CommonCache<K,V>;
}

export type OptimisticWrapOptions<
TArgs extends any[],
Expand All @@ -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<TCacheKey>, NoInfer<TResult>, NoInfer<TArgs>>
cache?: CommonCache<NoInfer<TCacheKey>, Entry<NoInfer<TArgs>, NoInfer<TResult>>>;
};

const caches = new Set<CommonCache<any, AnyEntry>>();
Expand All @@ -128,13 +125,11 @@ export function wrap<
makeCacheKey = (defaultMakeCacheKey as () => TCacheKey),
keyArgs,
subscribe,
Cache = StrongCache
}: OptimisticWrapOptions<TArgs, TKeyArgs, TCacheKey, TResult> = Object.create(null)) {
const cache = new Cache<TCacheKey, Entry<TArgs, TResult>>(
cache = new StrongCache(
max,
entry => entry.dispose(),
);

),
}: OptimisticWrapOptions<TArgs, TKeyArgs, TCacheKey, TResult> = Object.create(null)) {
const optimistic = function (): TResult {
const key = makeCacheKey.apply(
null,
Expand Down
9 changes: 3 additions & 6 deletions src/tests/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,8 @@ describe("optimism", function () {
});

it("can manually set the `Cache` implementation", () => {
let cache!: Cache<any, any>;

class Cache<K, V> implements CommonCache<K, V> {
private _cache = new Map<K, V>()
constructor() {
cache = this;
}
has = this._cache.has.bind(this._cache);
get = this._cache.get.bind(this._cache);
delete = this._cache.delete.bind(this._cache);
Expand All @@ -56,13 +51,15 @@ describe("optimism", function () {
clean(){};
}

const cache = new Cache<String, any>();

const wrapped = wrap(
(obj: { value: string }) => obj.value + " transformed",
{
cache,
makeCacheKey(obj) {
return obj.value;
},
Cache,
}
);
assert.ok(cache instanceof Cache);
Expand Down

0 comments on commit 789bdec

Please sign in to comment.