Skip to content

Commit e52532b

Browse files
committed
autocomplete [nfc]: Factor out compareNullable
1 parent e7d98b5 commit e52532b

File tree

2 files changed

+42
-6
lines changed

2 files changed

+42
-6
lines changed

lib/model/autocomplete.dart

+16-6
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,21 @@ class MentionAutocompleteView extends ChangeNotifier {
261261

262262
List<User>? _sortedUsers;
263263

264+
/// Compares [a] to [b].
265+
///
266+
/// If both are non-null, returns [a.compareTo(b)].
267+
///
268+
/// If one of them is null, returns a negative number if [a] is null and [b] is
269+
/// non-null and returns a positive number if [b] is null and [a] is non-null.
270+
///
271+
/// If both are null, returns zero.
272+
int compareNullable(int? a, int? b) => switch ((a, b)) {
273+
(int a, int b) => a.compareTo(b),
274+
(int(), _) => 1,
275+
(_, int()) => -1,
276+
_ => 0,
277+
};
278+
264279
/// Determines which of the two users is more recent in DM conversations.
265280
///
266281
/// Returns a negative number if [userA] is more recent than [userB],
@@ -272,12 +287,7 @@ class MentionAutocompleteView extends ChangeNotifier {
272287
final aLatestMessageId = recentDms.latestMessagesByRecipient[userA.userId];
273288
final bLatestMessageId = recentDms.latestMessagesByRecipient[userB.userId];
274289

275-
return switch((aLatestMessageId, bLatestMessageId)) {
276-
(int a, int b) => -a.compareTo(b),
277-
(int(), _) => -1,
278-
(_, int()) => 1,
279-
_ => 0,
280-
};
290+
return -compareNullable(aLatestMessageId, bLatestMessageId);
281291
}
282292

283293
int compareByRelevance({

test/model/autocomplete_test.dart

+26
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,32 @@ void main() {
465465
view = MentionAutocompleteView.init(store: store, narrow: narrow);
466466
}
467467

468+
group('MentionAutocompleteView.compareNullable', () {
469+
Future<void> prepareView() => prepare(
470+
users: [],
471+
dmConversations: [],
472+
narrow: const CombinedFeedNarrow(),
473+
);
474+
475+
test('both [a] and [b] are non-null', () async {
476+
await prepareView();
477+
check(view.compareNullable(2, 5)).isNegative();
478+
check(view.compareNullable(5, 2)).isGreaterThan(0);
479+
check(view.compareNullable(5, 5)).equals(0);
480+
});
481+
482+
test('one of [a] and [b] is null', () async {
483+
await prepareView();
484+
check(view.compareNullable(null, 5)).isNegative();
485+
check(view.compareNullable(5, null)).isGreaterThan(0);
486+
});
487+
488+
test('both of [a] and [b] are null', () async {
489+
await prepareView();
490+
check(view.compareNullable(null, null)).equals(0);
491+
});
492+
});
493+
468494
group('MentionAutocompleteView.compareByDms', () {
469495
test('has DMs with userA and userB, latest with userA, prioritizes userA', () async {
470496
await prepare(

0 commit comments

Comments
 (0)