Line data Source code
1 : import 'dart:collection'; 2 : 3 : /// Simple class to cache values with size based eviction. 4 : /// 5 : class MemoryCache<K, V> { 6 : final LinkedHashMap<K, V> _cache = LinkedHashMap(); 7 : final int cacheSize; 8 : 9 2 : MemoryCache({this.cacheSize = 10}); 10 : 11 2 : void setValue(K key, V value) { 12 4 : if (!_cache.containsKey(key)) { 13 4 : _cache[key] = value; 14 : 15 8 : while (_cache.length > cacheSize) { 16 3 : final k = _cache.keys.first; 17 2 : _cache.remove(k); 18 : } 19 : } 20 : } 21 : 22 6 : V? getValue(K key) => _cache[key]; 23 : 24 6 : bool containsKey(K key) => _cache.containsKey(key); 25 : 26 3 : int get size => _cache.length; 27 : }