Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 46 lines · 1.3 KiB · at 9c48a39

// Bug: truthiness check on the cached value (0/"" reloaded) and invalidate ignores the in-flight load.export class LoadError extends Error {  readonly kind = "load_failed" as const;  constructor(public readonly reason: string) {    super(reason);  }}export class CacheError extends Error {  readonly kind = "invalid_ttl" as const;  constructor() {    super("invalid_ttl");  }}export type Cache<V> = {  get(key: string): Promise<V>;  invalidate(key: string): void;};export function createCache<V>(loader: (key: string) => Promise<V>, ttlMs: number, now: () => number): Cache<V> {  if (!(ttlMs > 0)) throw new CacheError();  const values = new Map<string, V>();  const loadedAt = new Map<string, number>();  const inflight = new Map<string, Promise<V>>();  return {    async get(key) {      const v = values.get(key);      if (v && now() - loadedAt.get(key)! < ttlMs) return v;      if (inflight.has(key)) return inflight.get(key)!;      const p = loader(key)        .then((value) => {          values.set(key, value);          loadedAt.set(key, now());          return value;        })        .finally(() => inflight.delete(key));      inflight.set(key, p);      return p;    },    invalidate(key) {      values.delete(key);      loadedAt.delete(key);    },  };}