disjoint function
Returns true if a
and b
have no common elements.
Example
disjoint([1, 2], [3, 4]); // true
disjoint([1, 2], []); // true
disjoint([1, 2], [2, 3]); // false
Implementation details
This function assumes that the iterables have efficient length computations, i.e. the length is cached. This is true for most standard library collections.
Implementation
@useResult bool disjoint(Iterable<Object?> a, Iterable<Object?> b) {
if (a.isEmpty || b.isEmpty) {
return true;
}
final (iterable, contains) = switch ((a, b)) {
(_, _) when a is Set<Object?> || (b is! Set<Object?> && a.length > b.length) => (b, a),
_ => (a, b),
};
for (final element in iterable) {
if (contains.contains(element)) {
return false;
}
}
return true;
}