From d1301b9a8deca9215543c3927eacadc39baf04c3 Mon Sep 17 00:00:00 2001 From: Arthur Miranda Date: Wed, 24 Jul 2024 18:34:33 -0300 Subject: [PATCH] add `ascending` to SortedList.thenBy --- lib/src/sorted_list.dart | 17 +++++++++++++++-- test/sorted_list_test.dart | 10 ++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/src/sorted_list.dart b/lib/src/sorted_list.dart index 8621def..52b9e70 100644 --- a/lib/src/sorted_list.dart +++ b/lib/src/sorted_list.dart @@ -1,4 +1,5 @@ import 'dart:math'; + import 'package:dartx/dartx.dart'; Comparator _getComparator( @@ -43,10 +44,22 @@ class SortedList extends _DelegatingList { /// 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 thenBy(Comparable Function(E element) selector) { - return SortedList.withSelector(this, selector, 1, _comparator); + SortedList thenBy( + Comparable Function(E element) selector, { + bool ascending = true, + }) { + return SortedList.withSelector( + this, + selector, + ascending ? 1 : -1, + _comparator, + ); } /// Returns a new list with all elements sorted according to previously diff --git a/test/sorted_list_test.dart b/test/sorted_list_test.dart index 86539bd..8f38ed5 100644 --- a/test/sorted_list_test.dart +++ b/test/sorted_list_test.dart @@ -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);