mergePatch function

Json mergePatch(
  1. Json base,
  2. Json patch, {
  3. bool keepNulls = false,
})

base with patch merged in (RFC 7386): maps merge recursively, a null value removes the key (kept as null with keepNulls, to merge two patches), anything else replaces.

Implementation

Json mergePatch(Json base, Json patch, {bool keepNulls = false}) {
  final out = <String, Object?>{...base};
  for (final e in patch.entries) {
    final v = e.value, cur = out[e.key];
    if (v == null && !keepNulls) {
      out.remove(e.key);
    } else if (v is Map && cur is Map) {
      out[e.key] = mergePatch(readMap(cur)!, readMap(v)!, keepNulls: keepNulls);
    } else if (v is Map && !keepNulls) {
      // Over a value that is not a map, a map is merged into an empty one,
      // as RFC 7386 says: its nulls are not kept (`{"fill": 0, "hug": null}`
      // over a width of 310 stayed with both keys, a width of nothing).
      out[e.key] = mergePatch(const {}, readMap(v)!);
    } else {
      out[e.key] = v;
    }
  }
  return out;
}