traverseMap function

dynamic traverseMap(
  1. Map map,
  2. Iterable keys, {
  3. dynamic newValue,
})

Traverses a Map using a list of keys. If the keys do not exist, they are created. If newValue is provided, the value at the end of the traversal is set to newValue.

Returns the value at the end of the traversal.

Implementation

dynamic traverseMap(
  Map<dynamic, dynamic> map,
  Iterable<dynamic> keys, {
  dynamic newValue,
}) {
  dynamic current = map;
  for (var n = 0; n < keys.length; n++) {
    final key = keys.elementAt(n);
    if (n == keys.length - 1) {
      if (current is! Map) return null;
      if (newValue != null) {
        current[key] = newValue;
        return newValue;
      } else {
        return current[key];
      }
    } else {
      if (current is Map && current.containsKey(key)) {
        current = current[key];
      } else if (current is Map && newValue != null) {
        final next = <dynamic, dynamic>{};
        current[key] = next;
        current = next;
      } else {
        return null;
      }
    }
  }
  return null;
}