onCapacity method

  1. @override
void onCapacity(
  1. K key,
  2. V element
)

called if we want to insert another item denoted by key and element into the map. This method checks if the capacity is reached and eventually evicts old items.

Implementation

@override
void onCapacity(K key, V element) {
  if (length < capacity) return;
  // Iterate on all keys, so the eviction is O(n) to allow an insertion at O(1)
  LfuCacheEntry<K, V> min = storage.entries
      .map((e) => e as LfuCacheEntry<K, V>)
      .reduce((element1, element2) =>
          element1.use < element2.use ? element1 : element2);

  storage.onCapacity(min.key);
}