All files / src/util lru-cache.ts

100% Statements 43/43
100% Branches 16/16
100% Functions 8/8
100% Lines 43/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                1x 23x 23x   23x 23x 23x 23x         23x 36x 13x 13x   23x 23x 23x 23x 36x         23x   1043x 1x 1x   1043x 4x 1043x   9x 9x 9x 9x 9x 1042x 1043x         23x 2x 2x         23x 2x 2x         23x 1x 1x         23x 12x 12x 23x  
/**
 * Generic LRU cache
 *
 * Used for regex caching in OperatorMatches and JavaRegexConverter.
 * Evicts least recently used entry when capacity limit is reached.
 *
 * @param capacity maximum number of cached entries
 */
export class LRUCache<K, V> {
  private readonly capacity: number;
  private readonly map: Map<K, V>;
 
  constructor(capacity: number) {
    this.capacity = capacity;
    this.map = new Map<K, V>();
  }
 
  /**
   * Get cached value. If present, marks it as recently used.
   */
  public get(key: K): V | undefined {
    if (!this.map.has(key)) {
      return undefined;
    }
    // Map iteration order = insertion order; delete+reinsert to move to end
    const value = this.map.get(key)!;
    this.map.delete(key);
    this.map.set(key, value);
    return value;
  }
 
  /**
   * Set cached value. Evicts least recently used entry if capacity exceeded.
   */
  public set(key: K, value: V): void {
    // Capacity 0 stores nothing
    if (this.capacity === 0) {
      return;
    }
 
    if (this.map.has(key)) {
      this.map.delete(key);
    } else if (this.map.size >= this.capacity) {
      // Evict oldest entry (first in Map iteration)
      const oldestKey = this.map.keys().next().value;
      if (oldestKey !== undefined) {
        this.map.delete(oldestKey);
      }
    }
    this.map.set(key, value);
  }
 
  /**
   * Check if key exists
   */
  public has(key: K): boolean {
    return this.map.has(key);
  }
 
  /**
   * Delete specified key
   */
  public delete(key: K): boolean {
    return this.map.delete(key);
  }
 
  /**
   * Clear cache
   */
  public clear(): void {
    this.map.clear();
  }
 
  /**
   * Current cache entry count
   */
  public get size(): number {
    return this.map.size;
  }
}