From fd91b6721332cf19610e5b9b034d4ad788189c8d Mon Sep 17 00:00:00 2001 From: Arthur Miranda Date: Thu, 5 Dec 2024 21:49:42 -0300 Subject: [PATCH] add `ascending` to IterableExtension.sortedBy --- pkgs/collection/lib/src/iterable_extensions.dart | 12 ++++++++---- pkgs/collection/test/extensions_test.dart | 10 ++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/pkgs/collection/lib/src/iterable_extensions.dart b/pkgs/collection/lib/src/iterable_extensions.dart index 10f46760..6c060695 100644 --- a/pkgs/collection/lib/src/iterable_extensions.dart +++ b/pkgs/collection/lib/src/iterable_extensions.dart @@ -6,7 +6,6 @@ import 'dart:math' show Random; import 'algorithms.dart'; import 'functions.dart' as functions; -import 'utils.dart'; /// Extensions that apply to all iterables. /// @@ -71,10 +70,15 @@ extension IterableExtension on Iterable { /// Creates a sorted list of the elements of the iterable. /// /// The elements are ordered by the natural ordering of the - /// property [keyOf] of the element. - List sortedBy>(K Function(T element) keyOf) { + /// [keyOf] property when [ascending] is `true` or reverse ordering + /// when [ascending] is `false`. + List sortedBy>( + K Function(T element) keyOf, { + bool ascending = true, + }) { + int compare(K a, K b) => ascending ? a.compareTo(b) : b.compareTo(a); var elements = [...this]; - mergeSortBy(elements, keyOf, compareComparable); + mergeSortBy(elements, keyOf, compare); return elements; } diff --git a/pkgs/collection/test/extensions_test.dart b/pkgs/collection/test/extensions_test.dart index 6c5b45f1..e7eb2455 100644 --- a/pkgs/collection/test/extensions_test.dart +++ b/pkgs/collection/test/extensions_test.dart @@ -64,6 +64,16 @@ void main() { test('multiple', () { expect(iterable([3, 20, 100]).sortedBy(toString), [100, 20, 3]); }); + test('multiple ascending', () { + expect( + iterable([3, 20, 100]).sortedBy(toString, ascending: true), + [100, 20, 3]); + }); + test('multiple descending', () { + expect( + iterable([3, 20, 100]).sortedBy(toString, ascending: false), + [3, 20, 100]); + }); }); group('.sortedByCompare', () { test('empty', () {