lru_map.dart 769 B

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