compareObject<T extends Object> function
The compareObject comparator is similar to the natural comparator provided by Comparable objects in their Comparable.compareTo method, to sort objects in their "natural order". The difference here is that compareObject is also able to compare some objects which are not Comparable, such as bool, MapEntry, and nulls.
In more detail:
-
If
aandbare bothnull, they don't have order. If only one of them isnull, it will come later, unless thenullsBeforeistrue, in which case thenullwill come before. -
Otherwise, if
aandbare both of type Comparable, compare them with their natural comparator: Comparable.compareTo. -
Otherwise, if
aandbare map-entries (MapEntry), compare by theirkeys. If theirkeys are equal, then compare by theirvalues. -
Otherwise, if
aandbare booleans, compare them such astruecomes afterfalse. -
Otherwise, return
0, which means unordered.
Example:
[2, null, 1]..sort(compareObject);
Example with nulls coming before:
[2, null, 1]..sort((a, b) => compareObject(a, b, nullsBefore: true));
Implementation
int compareObject<T extends Object>(
Object? a,
Object? b, {
bool nullsBefore = false,
}) {
if (a == null)
return (b == null) ? 0 : (nullsBefore ? -1 : 1);
else if (b == null) return (nullsBefore ? 1 : -1);
if (a is Comparable && b is Comparable) return a.compareTo(b);
if (a is MapEntry && b is MapEntry)
return compareObject(a.key, b.key).if0(compareObject(a.value, b.value));
if (a is bool && b is bool) return a.compareTo(b);
return 0;
}