Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

randomOrNull() #177

Merged
merged 2 commits into from
Oct 25, 2021
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
11 changes: 11 additions & 0 deletions lib/src/collection/kt_collection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ extension KtCollectionExtensions<T> on KtCollection<T> {
return elementAt(r.nextInt(size));
}

/// Returns a random element from this collection.
///
/// 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;
return elementAt(index);
}

/// Returns a [KtMutableList] filled with all elements of this collection.
KtMutableList<T> toMutableList() => KtMutableList<T>.from(iter);
}
Expand Down
33 changes: 33 additions & 0 deletions test/collection/collection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,39 @@ void testCollection(KtCollection<T> Function<T>() emptyCollection,
});
});

group("randomOrNull", () {
test("random item or null with random parameter", () {
final collection = collectionOf(["a", "b", "c"]);

final firstPick = collection.randomOrNull(NotRandom()..next = 2);
final pos2 = collection.elementAt(2);
if (ordered) expect(pos2, "c");

expect(firstPick, pos2);

final pos0 = collection.elementAt(0);
if (ordered) expect(pos0, "a");

final secondPick = collection.randomOrNull(NotRandom()..next = 0);
expect(secondPick, pos0);

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", () {
if (ordered) {
test("default string representation", () {
Expand Down