Skip to content

Commit

Permalink
Add Iterable.occurrences helper.
Browse files Browse the repository at this point in the history
  • Loading branch information
renggli committed Dec 1, 2024
1 parent 2550771 commit 310c648
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/src/collection/iterable/count.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,14 @@ extension CountIterableExtension<E> on Iterable<E> {
/// [1, 2, 3].count((element) => element.isOdd);
/// ```
int count(bool Function(E element) predicate) => where(predicate).length;

/// Returns the number of times [element] appears in the iterable.
///
/// The following expression yields 2, because the number 5 appears
/// twice:
///
/// ```dart
/// [1, 5, 4, 5, 2].occurrences(5);
/// ```
int occurrences(E element) => count((each) => each == element);
}
2 changes: 1 addition & 1 deletion lib/src/collection/sortedlist.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class SortedList<E> extends ListBase<E> implements PriorityQueue<E> {
bool contains(Object? element) =>
element is E && _comparator.binarySearch(_values, element) >= 0;

/// Returns the number of times the element appears in the sorted list.
/// Returns the number of times [element] appears in the list.
int occurrences(E element) {
final lower = _comparator.binarySearchLower(_values, element);
final upper = _comparator.binarySearchUpper(_values, element);
Expand Down
6 changes: 6 additions & 0 deletions test/collection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -933,6 +933,12 @@ void main() {
expect(<int>[1, 2, 3].count((each) => each.isOdd), 2);
expect(<int>[1, 2, 3, 4, 5].count((each) => each.isOdd), 3);
});
test('occurrences', () {
expect(<int>[].occurrences(5), 0);
expect(<int>[5].occurrences(5), 1);
expect(<int>[1].occurrences(5), 0);
expect(<int>[1, 5, 4, 5, 2].occurrences(5), 2);
});
});
group('flatMap', () {
test('empty', () {
Expand Down

0 comments on commit 310c648

Please sign in to comment.