Skip to content

Commit

Permalink
add ascending to SortedList.thenBy
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurbcd committed Jul 24, 2024
1 parent 3671b50 commit d1301b9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lib/src/sorted_list.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:math';

import 'package:dartx/dartx.dart';

Comparator<E> _getComparator<E>(
Expand Down Expand Up @@ -43,10 +44,22 @@ class SortedList<E> extends _DelegatingList<E> {
/// defined order and natural sort order of the values returned by specified
/// [selector] function.
///
/// The [ascending] parameter controls the order of sorting:
/// - Defaults to `true`, sorting elements in ascending order.
/// - Set to `false` to sort elements in descending order.
///
/// **Note:** The actual sorting is performed when an element is accessed for
/// the first time.
SortedList<E> thenBy(Comparable Function(E element) selector) {
return SortedList<E>.withSelector(this, selector, 1, _comparator);
SortedList<E> thenBy(
Comparable Function(E element) selector, {
bool ascending = true,
}) {
return SortedList<E>.withSelector(
this,
selector,
ascending ? 1 : -1,
_comparator,
);
}

/// Returns a new list with all elements sorted according to previously
Expand Down
10 changes: 10 additions & 0 deletions test/sorted_list_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ void main() {
final thenByDesc = list.thenByDescending((it) => it);
expect(thenByDesc, ['c', 'ba', 'aa']);
});

test('thenBy, ascending', () {
final list = ['ba', 'c', 'aa'].sortedBy((it) => it.length);
expect(list, ['c', 'ba', 'aa']);
final thenBy = list.thenBy((it) => it, ascending: true);
expect(thenBy, ['c', 'aa', 'ba']);
final thenByDesc = list.thenBy((it) => it, ascending: false);
expect(thenByDesc, ['c', 'ba', 'aa']);
});

group('_DelegatingIterable', () {
test('any', () {
expect(_sortedList.any((it) => it > 2), isTrue);
Expand Down

0 comments on commit d1301b9

Please sign in to comment.