Skip to content

Commit 51ca549

Browse files
committed
autocomplete [nfc]: Factor out compareNullable
1 parent 39b89bf commit 51ca549

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

lib/model/autocomplete.dart

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,14 +204,24 @@ class MentionAutocompleteView extends ChangeNotifier {
204204
final aLatestMessageId = recentDms.latestMessagesByRecipient[userA.userId];
205205
final bLatestMessageId = recentDms.latestMessagesByRecipient[userB.userId];
206206

207-
return switch((aLatestMessageId, bLatestMessageId)) {
208-
(int a, int b) => -a.compareTo(b),
209-
(int(), _) => -1,
210-
(_, int()) => 1,
211-
_ => 0,
212-
};
207+
return -compareNullable(aLatestMessageId, bLatestMessageId);
213208
}
214209

210+
/// Compares [a] to [b].
211+
///
212+
/// If both are non-null, returns [a.compareTo(b)].
213+
///
214+
/// If one of them is null, returns a negative number if [a] is null and [b] is
215+
/// non-null and returns a positive number if [b] is null and [a] is non-null.
216+
///
217+
/// If both are null, returns zero.
218+
static int compareNullable(int? a, int? b) => switch ((a, b)) {
219+
(int a, int b) => a.compareTo(b),
220+
(int(), _) => 1,
221+
(_, int()) => -1,
222+
_ => 0,
223+
};
224+
215225
@override
216226
void dispose() {
217227
store.autocompleteViewManager.unregisterMentionAutocomplete(this);

test/model/autocomplete_test.dart

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,23 @@ void main() {
364364
await store.addUsers(users);
365365
}
366366

367+
group('MentionAutocompleteView.compareNullable', () {
368+
test('both [a] and [b] are non-null', () async {
369+
check(MentionAutocompleteView.compareNullable(2, 5)).isLessThan(0);
370+
check(MentionAutocompleteView.compareNullable(5, 2)).isGreaterThan(0);
371+
check(MentionAutocompleteView.compareNullable(5, 5)).equals(0);
372+
});
373+
374+
test('one of [a] and [b] is null', () async {
375+
check(MentionAutocompleteView.compareNullable(null, 5)).isLessThan(0);
376+
check(MentionAutocompleteView.compareNullable(5, null)).isGreaterThan(0);
377+
});
378+
379+
test('both of [a] and [b] are null', () async {
380+
check(MentionAutocompleteView.compareNullable(null, null)).equals(0);
381+
});
382+
});
383+
367384
group('MentionAutocompleteView.compareByDms', () {
368385
const idA = 1;
369386
const idB = 2;

0 commit comments

Comments
 (0)