import { IRef, Params, SubFn } from "./model"; /** * Each subscription maintains its own cache of active subscriptions based * on the params passed to it. * * TODO do we need to support a global clearSubscriptionCaches method? */ export interface ISubCache { /** * Get a cached reference of the sub for the given params, if any exists */ get(params: P): IRef | undefined; /** * Store a cached reference */ put(params: P, ref: IRef): void; /** * Delete the cached reference for the given sub */ delete(params: P): void; } class SimpleSubCache implements ISubCache { private cache = new Map>(); constructor( private toKey: ((params: P) => string) = JSON.stringify, ) {} get(params: P): IRef | undefined { return this.cache.get(this.toKey(params)); } put(params: P, ref: IRef) { this.cache.set(this.toKey(params), ref); } delete(params: P) { this.cache.delete(this.toKey(params)); } } export function createCacheFor( fn: SubFn, ): ISubCache { // TODO would it be worth it to optimize for the 0-arg and 1-arg cases? return new SimpleSubCache(); }