Skip to content

Commit

Permalink
--add: randomOrNull()
Browse files Browse the repository at this point in the history
  • Loading branch information
Rishabh-Negi committed Oct 25, 2021
1 parent a78b16f commit 9390e38
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/src/collection/kt_collection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ 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]) {
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
26 changes: 26 additions & 0 deletions test/collection/collection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,32 @@ 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);
});

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

0 comments on commit 9390e38

Please sign in to comment.