remove method

  1. @override
V? remove(
  1. Object? key
)
override

Removes key and its associated value, if present, from the map.

Returns the value associated with key before it was removed. Returns null if key was not in the map.

Note that some maps allow null as a value, so a returned null value doesn't always mean that the key was absent.

final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
final removedValue = terrestrial.remove(2); // Venus
print(terrestrial); // {1: Mercury, 3: Earth}

Implementation

@override
V? remove(Object? key) {
  if (key is K) {
    final parts = <P>[];
    final nodes = <TrieNode<K, P, V>>[_root];
    // Navigate to the right node.
    for (final part in _getParts(key)) {
      final node = nodes.last.getChild(part);
      if (node == null) {
        return null;
      }
      parts.add(part);
      nodes.add(node);
    }
    // Verify we found a value node.
    var current = nodes.removeLast();
    if (current.hasKeyAndValue) {
      // Remove the value from the tree.
      final value = current.value;
      current.clearKeyAndValue();
      _length--;
      // Cleanup no longer needed subtrees.
      while (nodes.isNotEmpty &&
          parts.isNotEmpty &&
          !current.hasKeyAndValue &&
          !current.hasChildren) {
        current = nodes.removeLast();
        current.removeChild(parts.removeLast());
      }
      // Return the value of the remove node.
      return value;
    }
  }
  return null;
}