Skip to content

Commit

Permalink
refactor(cache): add MapLike interface to loosen Map impls
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Oct 31, 2024
1 parent 8301254 commit 603c76c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
13 changes: 12 additions & 1 deletion packages/cache/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export interface CacheOpts<K, V> {
* Custom ES6 Map compatible implementation to use as the cache's backing
* store.
*/
map: Fn0<Map<K, any>>;
map: Fn0<MapLike<K, any>>;
/**
* Max number of items in the cache.
*/
Expand All @@ -115,3 +115,14 @@ export interface CacheEntry<K, V> {
v: V;
s: number;
}

/**
* Simplified subset of the ES6 Map API needed for cache implementations.
*/
export interface MapLike<K, V> {
has(key: K): boolean;
get(key: K): Maybe<V>;
set(key: K, val: V): void;
delete(key: K): void;
clear(): void;
}
4 changes: 2 additions & 2 deletions packages/cache/src/lru.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { Fn0, Maybe, Nullable } from "@thi.ng/api";
import type { ConsCell } from "@thi.ng/dcons";
import { DCons } from "@thi.ng/dcons/dcons";
import type { CacheEntry, CacheOpts, ICache } from "./api.js";
import type { CacheEntry, CacheOpts, ICache, MapLike } from "./api.js";

export class LRUCache<K, V> implements ICache<K, V> {
protected map: Map<K, ConsCell<CacheEntry<K, V>>>;
protected map: MapLike<K, ConsCell<CacheEntry<K, V>>>;
protected items: DCons<CacheEntry<K, V>>;
protected opts: CacheOpts<K, V>;
protected _size: number;
Expand Down
4 changes: 2 additions & 2 deletions packages/cache/src/tlru.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Fn0, Maybe, Nullable } from "@thi.ng/api";
import type { ConsCell, DCons } from "@thi.ng/dcons";
import type { CacheEntry, CacheOpts } from "./api.js";
import type { CacheEntry, CacheOpts, MapLike } from "./api.js";
import { LRUCache } from "./lru.js";

export interface TLRUCacheOpts<K, V> extends CacheOpts<K, V> {
Expand Down Expand Up @@ -50,7 +50,7 @@ export interface TLRUCacheEntry<K, V> extends CacheEntry<K, V> {
*/
export class TLRUCache<K, V> extends LRUCache<K, V> {
protected declare opts: TLRUCacheOpts<K, V>;
protected declare map: Map<K, ConsCell<TLRUCacheEntry<K, V>>>;
protected declare map: MapLike<K, ConsCell<TLRUCacheEntry<K, V>>>;
protected declare items: DCons<TLRUCacheEntry<K, V>>;

constructor(
Expand Down

0 comments on commit 603c76c

Please sign in to comment.