Skip to content

Instantly share code, notes, and snippets.

@pongloongyeat
Last active August 23, 2023 03:12
Show Gist options
  • Save pongloongyeat/f88f3a573a752f15ec3aa043ec9f339d to your computer and use it in GitHub Desktop.
Save pongloongyeat/f88f3a573a752f15ec3aa043ec9f339d to your computer and use it in GitHub Desktop.
Map.contains
import 'package:collection/collection.dart';
extension ListExtension<E> on List<E> {
/// Checks whether every element of this iterable satisfies [test] while
/// passing the element and the index to [test].
bool everyIndexed(bool Function(int index, E element) test) {
for (var i = 0; i < length; i++) {
final element = this[i];
if (!test(i, element)) return false;
}
return true;
}
}
typedef Json = Map<String, dynamic>;
extension JsonContains on Json {
/// Checks if the current JSON map contains [other]. By default, this will
/// skip undefined keys that are not present in the current JSON map. If
/// [skipUndefinedKeys] is `false`, this will return false if there are
/// undefined keys present in [other] that is not present in the current
/// JSON map.
///
/// ```dart
/// final a = {'a': 1, 'b': 2, 'c': 3};
/// final b = {'a': 1, 'b': 2, 'd': 4};
///
/// print(a.contains(b)); // returns true
/// print(a.contains(b, skipUndefinedKeys: false)); // returns false
/// ```
bool contains(
Json other, {
bool skipUndefinedKeys = true,
}) {
return other.entries.every((entry) {
if (!containsKey(entry.key)) {
return skipUndefinedKeys;
}
final thisValue = this[entry.key];
final otherValue = entry.value;
if (thisValue is List &&
otherValue is List &&
thisValue.firstOrNull is Map &&
otherValue.firstOrNull is Map) {
return thisValue.everyIndexed((index, _) {
final ithValue = thisValue[index] as Json;
final ithOtherValue = otherValue[index] as Json;
return ithValue.contains(
ithOtherValue,
skipUndefinedKeys: skipUndefinedKeys,
);
});
}
if (thisValue is Map && otherValue is Map) {
return (thisValue as Json).contains(otherValue as Json);
}
return const DeepCollectionEquality().equals(thisValue, otherValue);
});
}
}
void main() {
final a = {'a': 1, 'b': 2, 'c': 3};
final b = {'a': 1, 'b': 2, 'd': 4};
print(a.contains(b)); // returns true
print(a.contains(b, skipUndefinedKeys: false)); // returns false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment