operator []= method

void operator []=(
  1. K key,
  2. V value
)

Insert/update; evicts LRU if the cache is full.

Implementation

void operator []=(K key, V value) {
  final existing = _nodes[key];
  if (existing != null) {
    final old = existing.value;
    existing.value = value;
    _moveToNewest(existing);
    if (!identical(old, value) && old != null) onEvict?.call(old);
    return;
  }
  if (_nodes.length == capacity) {
    final eldest = _head.next as _LruNode<K, V>;
    _unlink(eldest);
    _nodes.remove(eldest.key);
    final evicted = eldest.value;
    if (evicted != null) onEvict?.call(evicted);
  }
  final node = _LruNode<K, V>(key, value);
  _nodes[key] = node;
  _linkNewest(node);
}