Line data Source code
1 : /// A node in the trie containing multiple child nodes. 2 : /// 3 : /// [K] is the key and is unique relative to the parent, not the entire data 4 : /// structure. [V] is an element stored in the Trie. 5 : class TrieNode<K, V> { 6 : final Map<K, TrieNode<K, V>> _children; 7 : final K key; 8 : V value; 9 : 10 20 : TrieNode(this.key, this.value) : _children = {}; 11 : 12 10 : bool contains(K key) { 13 20 : return _children.containsKey(key); 14 : } 15 : 16 10 : void add(K key, V value) { 17 30 : _children[key] = TrieNode<K, V>(key, value); 18 : } 19 : 20 10 : TrieNode<K, V>? get(K key) { 21 40 : return _children.containsKey(key) ? _children[key] : null; 22 : } 23 : 24 6 : bool containsWhere(bool Function(K k) test) { 25 18 : for (var childKey in _children.keys) { 26 : if (childKey == null) continue; 27 5 : if (test(childKey)) { 28 : return true; 29 : } 30 : } 31 : return false; 32 : } 33 : 34 4 : TrieNode<K, V>? getWhere(bool Function(K k) test) { 35 12 : for (var childKey in _children.keys) { 36 4 : if (test(childKey)) { 37 8 : return _children[childKey]; 38 : } 39 : } 40 : return null; 41 : } 42 : } 43 : 44 : /// A Trie that associates an [Iterable] of keys, [K] with a value, [V]. 45 : /// 46 : /// Keys must be unique relative to their prefix. For example, for a 47 : /// Trie<String, String> if the following add() operations are valid: 48 : /// 49 : /// ```dart 50 : /// add(['users', 'greg'], 'value'); 51 : /// add(['customers', 'greg'], 'value'); // OK 52 : /// ``` 53 : class Trie<K, V> { 54 : final TrieNode<K?, V?> root; 55 : 56 20 : Trie() : root = TrieNode<K?, V?>(null, null); 57 : }