Skip to content

Commit 3457070

Browse files
committed
autocomplete [nfc]: Factor out compareNullable
1 parent 0289061 commit 3457070

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

lib/model/autocomplete.dart

+15-6
Original file line numberDiff line numberDiff line change
@@ -204,14 +204,23 @@ 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+
/// If [a] is null and [b] is non-null, returns a negative number.
214+
/// If [a] is non-null and [b] is null, returns a positive number.
215+
/// If both are null, returns zero.
216+
@visibleForTesting
217+
static int compareNullable(int? a, int? b) => switch ((a, b)) {
218+
(int a, int b) => a.compareTo(b),
219+
(int(), _) => 1,
220+
(_, int()) => -1,
221+
_ => 0,
222+
};
223+
215224
@override
216225
void dispose() {
217226
store.autocompleteViewManager.unregisterMentionAutocomplete(this);

test/model/autocomplete_test.dart

+17
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,23 @@ void main() {
365365
await store.addUsers(users);
366366
}
367367

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

0 commit comments

Comments
 (0)