Skip to content

Commit fd91b67

Browse files
committed
add ascending to IterableExtension.sortedBy
1 parent 7f9f597 commit fd91b67

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

pkgs/collection/lib/src/iterable_extensions.dart

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import 'dart:math' show Random;
66

77
import 'algorithms.dart';
88
import 'functions.dart' as functions;
9-
import 'utils.dart';
109

1110
/// Extensions that apply to all iterables.
1211
///
@@ -71,10 +70,15 @@ extension IterableExtension<T> on Iterable<T> {
7170
/// Creates a sorted list of the elements of the iterable.
7271
///
7372
/// The elements are ordered by the natural ordering of the
74-
/// property [keyOf] of the element.
75-
List<T> sortedBy<K extends Comparable<K>>(K Function(T element) keyOf) {
73+
/// [keyOf] property when [ascending] is `true` or reverse ordering
74+
/// when [ascending] is `false`.
75+
List<T> sortedBy<K extends Comparable<K>>(
76+
K Function(T element) keyOf, {
77+
bool ascending = true,
78+
}) {
79+
int compare(K a, K b) => ascending ? a.compareTo(b) : b.compareTo(a);
7680
var elements = [...this];
77-
mergeSortBy<T, K>(elements, keyOf, compareComparable);
81+
mergeSortBy<T, K>(elements, keyOf, compare);
7882
return elements;
7983
}
8084

pkgs/collection/test/extensions_test.dart

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,16 @@ void main() {
6464
test('multiple', () {
6565
expect(iterable(<int>[3, 20, 100]).sortedBy(toString), [100, 20, 3]);
6666
});
67+
test('multiple ascending', () {
68+
expect(
69+
iterable(<int>[3, 20, 100]).sortedBy(toString, ascending: true),
70+
[100, 20, 3]);
71+
});
72+
test('multiple descending', () {
73+
expect(
74+
iterable(<int>[3, 20, 100]).sortedBy(toString, ascending: false),
75+
[3, 20, 100]);
76+
});
6777
});
6878
group('.sortedByCompare', () {
6979
test('empty', () {

0 commit comments

Comments
 (0)