lru_map.dart 761 B

1234567891011121314151617181920212223242526272829303132333435
  1. import 'dart:collection';
  2. typedef EvictionHandler<K, V> = Function(K key, V value);
  3. class LRUMap<K, V> {
  4. final LinkedHashMap<K, V> _map = LinkedHashMap<K, V>();
  5. final int _maxSize;
  6. final EvictionHandler<K, V?>? _handler;
  7. LRUMap(this._maxSize, [this._handler]);
  8. V? get(K key) {
  9. final V? value = _map.remove(key);
  10. if (value != null) {
  11. _map[key] = value;
  12. }
  13. return value;
  14. }
  15. void put(K key, V value) {
  16. _map.remove(key);
  17. _map[key] = value;
  18. if (_map.length > _maxSize) {
  19. final K evictedKey = _map.keys.first;
  20. final V? evictedValue = _map.remove(evictedKey);
  21. if (_handler != null) {
  22. _handler!(evictedKey, evictedValue);
  23. }
  24. }
  25. }
  26. void remove(K key) {
  27. _map.remove(key);
  28. }
  29. }