Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

888 B
Raw Blame
export class LruStringCache {
  private readonly map = new Map<string, string>();

  private readonly limit: number;

  constructor(limit: number) {
    this.limit = limit;
    if (limit <= 0) {
      throw new Error(`LruStringCache: limit must be > 0 (got ${limit})`);
    }
  }

  get(key: string): string | undefined {
    const value = this.map.get(key);
    if (value === undefined) return undefined;
    this.map.delete(key);
    this.map.set(key, value);
    return value;
  }

  set(key: string, value: string): void {
    if (this.map.has(key)) this.map.delete(key);
    this.map.set(key, value);
    while (this.map.size > this.limit) {
      const oldestKey = this.map.keys().next().value;
      if (oldestKey === undefined) break;
      this.map.delete(oldestKey);
    }
  }

  clear(): void {
    this.map.clear();
  }

  get size(): number {
    return this.map.size;
  }
}