mergeDataDeep function

dynamic mergeDataDeep(
  1. dynamic a,
  2. dynamic b, [
  3. dynamic elseFilter(
    1. dynamic
    )?
])

Deeply merges a and b. The returned structure does not share any mutable substructure with either input — mutating the result is safe and will not affect a or b.

Implementation

dynamic mergeDataDeep(
  dynamic a,
  dynamic b, [
  dynamic Function(dynamic)? elseFilter,
]) {
  if (a is Map && b is Map) {
    final result = <dynamic, dynamic>{};
    for (final key in a.keys) {
      result[key] = _deepCopy(a[key]);
    }
    for (final key in b.keys) {
      if (result.containsKey(key)) {
        result[key] = mergeDataDeep(result[key], b[key], elseFilter);
      } else {
        result[key] = mergeDataDeep(null, b[key], elseFilter);
      }
    }
    return result;
  }
  if ((a is List || a is Set || a is Queue) && b is Iterable) {
    return mergeListsSetsOrQueues(a as Iterable, b, elseFilter);
  }
  if (a is Iterable && b is Iterable) {
    return mergeIterables(a, b);
  }
  if (elseFilter != null) {
    return elseFilter(b);
  }
  // Default: b wins, but defensively deep-copy any mutable substructure
  // so the caller can't mutate `b` via the returned result.
  return _deepCopy(b);
}