Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Add IterableExtension.shuffled #298

Merged
merged 1 commit into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions lib/src/iterable_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ extension IterableExtension<T> on Iterable<T> {
/// 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
Expand Down
16 changes: 16 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,22 @@ void main() {
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), []);
Expand Down