Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 55 lines · 1.6 KiB · at 503e839

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> = {  /** Rejects with the loader's LoadError when the load fails. */  get(key: string): Promise<V>;  invalidate(key: string): void;};/** Throws CacheError when ttlMs is not a positive integer. `loader` rejects with a LoadError on failure. */export function createCache<V>(loader: (key: string) => Promise<V>, ttlMs: number, now: () => number): Cache<V> {  if (!Number.isInteger(ttlMs) || ttlMs <= 0) throw new CacheError();  const values = new Map<string, { value: V; loadedAt: number }>();  const inflight = new Map<string, Promise<V>>();  const get = (key: string): Promise<V> => {    const hit = values.get(key);    if (hit !== undefined && now() - hit.loadedAt < ttlMs) return Promise.resolve(hit.value);    const pending = inflight.get(key);    if (pending !== undefined) return pending;    const load: Promise<V> = loader(key).then(      (value) => {        if (inflight.get(key) === load) {          inflight.delete(key);          values.set(key, { value, loadedAt: now() });        }        return value;      },      (error: unknown) => {        if (inflight.get(key) === load) inflight.delete(key);        throw error;      },    );    inflight.set(key, load);    return load;  };  const invalidate = (key: string): void => {    values.delete(key);    inflight.delete(key);  };  return { get, invalidate };}