diff --git a/lib/src/comparisons.dart b/lib/src/comparisons.dart index b34c8e49..a7b8c744 100644 --- a/lib/src/comparisons.dart +++ b/lib/src/comparisons.dart @@ -20,30 +20,18 @@ Comparator reverse(Comparator comparator) { return compareTo; } -//class _ReversedComparator { -// _ReversedComparator(this.comparator); -// -// Comparator comparator; -// -// int compareTo(T a, T b) => comparator(b, a); -//} - +/** + * Creates a comparator using the function to transform value to a [Comparable] instance for comparison. + */ Comparator compareBy(Comparable Function(T) selector) { int compareTo(T a, T b) => selector(a).compareTo(selector(b)); - return compareTo; } +/** + * Creates a descending comparator using the function to transform value to a [Comparable] instance for comparison. + */ Comparator compareByDescending(Comparable Function(T) selector) { int compareTo(T a, T b) => selector(b).compareTo(selector(a)); - return compareTo; } - -//class _CompareBy { -// Comparable Function(T) selector; -// -// _CompareBy(this.selector); -// -// int compareTo(T a, T b) => selector(a).compareTo(selector(b)); -//} diff --git a/test/comparisons_test.dart b/test/comparisons_test.dart new file mode 100644 index 00000000..8879d924 --- /dev/null +++ b/test/comparisons_test.dart @@ -0,0 +1,28 @@ +import 'package:dart_kollection/dart_kollection.dart'; +import 'package:test/test.dart'; + +void main() { + group('compare in natural order', () { + test("naturalOrder", () { + final list = listOf([3, 4, 5, 2, 1]); + final natural = list.sortedWith(naturalOrder()); + expect(natural, listOf([1, 2, 3, 4, 5])); + }); + }); + + group('compare reversed order', () { + test("reverseOrder", () { + final list = listOf([3, 4, 5, 2, 1]); + final natural = list.sortedWith(reverseOrder()); + expect(natural, listOf([5, 4, 3, 2, 1])); + }); + }); + + group("reverse custom comparator", () { + test("reverse natural", () { + final list = listOf([3, 4, 5, 2, 1]); + final reversedNatural = list.sortedWith(reverse(naturalOrder())); + expect(reversedNatural, listOf([5, 4, 3, 2, 1])); + }); + }); +} diff --git a/test/dart_kollection_test.dart b/test/dart_kollection_test.dart index 79fd59cb..d21257fa 100644 --- a/test/dart_kollection_test.dart +++ b/test/dart_kollection_test.dart @@ -9,11 +9,13 @@ import 'collection/map_mutable_extensions_test.dart' as map_mutable_extensions_t import 'collection/map_test.dart' as map_test; import 'collection/set_test.dart' as set_test; import 'collections_test.dart' as collections_test; +import 'comparisons_test.dart' as comparisons_test; import 'exceptions_test.dart' as exceptions_test; import 'tuples_test.dart' as tuples_test; main() { collections_test.main(); + comparisons_test.main(); exceptions_test.main(); tuples_test.main(); iterable_extensions_test.main();