← 中文资源

简体中文版本

带淘汰回调的泛型缓存

构建对值类型泛型的键值缓存并触发淘汰回调,让调用方获得类型化读取并可清理资源。

阅读英文原文

实现说明

活动部件是类 TypedCache。

使用要点

  • 守卫 !entry 一旦成立就走提前的 return,把后续流程挡掉。
  • 值得导入的表面是 TypedCache;周围的辅助代码对片段是私有的。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。

核心语句

private store = new Map<K, { value: V; expiresAt: number }>();
this.onEvict?.(key, previous.value);
this.onEvict?.(key, entry.value);

代码示例

export class TypedCache<K, V> {
  private store = new Map<K, { value: V; expiresAt: number }>();

  constructor(
    private ttlMs: number,
    private onEvict?: (key: K, value: V) => void,
  ) {}

  get(key: K): V | undefined {
    const entry = this.store.get(key);
    if (!entry) return undefined;
    if (entry.expiresAt <= Date.now()) {
      this.store.delete(key);
      this.onEvict?.(key, entry.value);
      return undefined;
    }
    return entry.value;
  }

  set(key: K, value: V): void {
    if (this.store.has(key)) {
      const previous = this.store.get(key)!;
      this.onEvict?.(key, previous.value);
    }
    this.store.set(key, { value, expiresAt: Date.now() + this.ttlMs });
  }

  size(): number {
    return this.store.size;
  }
}