Skip to content

Commit

Permalink
--update: fix and test for empty collection for randomOrNull
Browse files Browse the repository at this point in the history
  • Loading branch information
Rishabh-Negi committed Oct 25, 2021
1 parent 9390e38 commit eda96a6
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/src/collection/kt_collection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ extension KtCollectionExtensions<T> on KtCollection<T> {
///
/// returns null if this collection is empty.
T? randomOrNull([math.Random? random]) {
if (!isNotEmpty()) return null;
final r = random ?? math.Random();
final index = r.nextInt(size);
if (index >= size) return null;
Expand Down
7 changes: 7 additions & 0 deletions test/collection/collection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,19 @@ void testCollection(KtCollection<T> Function<T>() emptyCollection,

final outOfRangePick = collection.randomOrNull(NotRandom()..next = 3);
expect(outOfRangePick, null);

final emptyCollection = collectionOf([]);
final pick1 = emptyCollection.randomOrNull(NotRandom()..next = 0);
expect(pick1, null);
});

test("randomOrNull works without passing a Random", () {
final collection = collectionOf(["a", "b", "c"]);
expect(collection.randomOrNull(),
anyOf(equals("a"), equals("b"), equals("c"), equals(null)));

final emptyCollection = collectionOf([]);
expect(emptyCollection.randomOrNull(), equals(null));
});
});
group("toString", () {
Expand Down

0 comments on commit eda96a6

Please sign in to comment.