All files / src/util lru-cache.ts

100% Statements 21/21
90% Branches 9/10
100% Functions 7/7
100% Lines 21/21

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                          23x 23x             36x 13x     23x 23x 23x 23x               1043x 1x     1042x 4x 1038x   9x 9x 9x     1042x             2x             2x             1x             12x      
/**
 * 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;
      Eif (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;
  }
}