From 0b21dd9287b19a283b90bf5e09f93a6b7ba99d1d Mon Sep 17 00:00:00 2001 From: Ebrahim Byagowi Date: Thu, 13 Jul 2023 17:57:23 +0330 Subject: [PATCH] Add IterableExtension.shuffled Creates a shuffled list of the elements of the iterable. --- CHANGELOG.md | 1 + lib/src/iterable_extensions.dart | 3 +++ test/extensions_test.dart | 16 ++++++++++++++++ 3 files changed, 20 insertions(+) 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` (with the original key values). - `toMapOfCanonicalKeys`: creates a `Map` (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 @@ extension IterableExtension on Iterable { /// The elements are ordered by the [compare] [Comparator]. List sorted(Comparator compare) => [...this]..sort(compare); + /// Creates a shuffled list of the elements of the iterable. + List 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 @@ void main() { expect(iterable([5, 2, 4, 3, 1]).sorted(cmpInt), [1, 2, 3, 4, 5]); }); }); + group('.shuffled', () { + test('empty', () { + expect(iterable([]).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([]).sortedBy(unreachable), []);