Add IterableExtension.shuffled (#298)
Creates a shuffled list of the elements of the iterable.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 428c2c5..f5b9279 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@
- `toMap`: creates a `Map<K,V>` (with the original key values).
- `toMapOfCanonicalKeys`: creates a `Map<C,V>` (with the canonicalized keys).
- Fixes bugs in `ListSlice.slice` and `ListExtensions.slice`.
+- Adds `shuffled` to `IterableExtension`.
- Update to `package:lints` 2.0.1.
## 1.17.2
diff --git a/lib/src/iterable_extensions.dart b/lib/src/iterable_extensions.dart
index 7772622..6e0be3c 100644
--- a/lib/src/iterable_extensions.dart
+++ b/lib/src/iterable_extensions.dart
@@ -58,6 +58,9 @@
/// The elements are ordered by the [compare] [Comparator].
List<T> sorted(Comparator<T> compare) => [...this]..sort(compare);
+ /// Creates a shuffled list of the elements of the iterable.
+ List<T> shuffled([Random? random]) => [...this]..shuffle(random);
+
/// Creates a sorted list of the elements of the iterable.
///
/// The elements are ordered by the natural ordering of the
diff --git a/test/extensions_test.dart b/test/extensions_test.dart
index 23bc321..d7a59a0 100644
--- a/test/extensions_test.dart
+++ b/test/extensions_test.dart
@@ -37,6 +37,22 @@
expect(iterable([5, 2, 4, 3, 1]).sorted(cmpInt), [1, 2, 3, 4, 5]);
});
});
+ group('.shuffled', () {
+ test('empty', () {
+ expect(iterable(<int>[]).shuffled(), []);
+ });
+ test('singleton', () {
+ expect(iterable([1]).shuffled(), [1]);
+ });
+ test('multiple', () {
+ var input = iterable([1, 2, 3, 4, 5]);
+ var copy = [...input];
+ var shuffled = input.shuffled();
+ expect(UnorderedIterableEquality().equals(input, shuffled), isTrue);
+ // Check that the original list isn't touched
+ expect(input, copy);
+ });
+ });
group('.sortedBy', () {
test('empty', () {
expect(iterable(<int>[]).sortedBy(unreachable), []);