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
a
andb
are bothnull
, they don't have order. If only one of them isnull
, it will come later, unless thenullsBefore
istrue
, in which case thenull
will come before. -
Otherwise, if
a
andb
are both of type Comparable, compare them with their natural comparator: Comparable.compareTo. -
Otherwise, if
a
andb
are map-entries (MapEntry), compare by theirkey
s. If theirkey
s are equal, then compare by theirvalue
s. -
Otherwise, if
a
andb
are booleans, compare them such astrue
comes afterfalse
. -
Otherwise, return
0
, which means unordered.
Example:
[2, null, 1]..sort(compareObject);
Example with null
s 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;
}