count method

int count([
  1. bool predicate(
    1. T element
    )?
])

Counts the number of elements in the current Iterable that satisfy the given predicate.

The function takes an optional predicate parameter, which represents a function that tests each element in the Iterable. If the predicate is not provided, it returns the length of the Iterable. If the predicate is provided, it iterates over each element in the Iterable and counts the elements that satisfy the given predicate.

Returns the count of elements that satisfy the predicate function, or the length of the Iterable if no predicate is provided.

Example:

List<int> numbers = [1, 2, 3, 4, 5];
int countAll = numbers.count(); // Count all elements in the list
int countEven = numbers.count((number) => number % 2 == 0); // Count even numbers
print(countAll); // Output: 5
print(countEven); // Output: 2

Implementation

int count([bool predicate(T element)?]) {
  var count = 0;
  if (predicate == null) {
    return length;
  } else {
    for (var current in this) {
      if (predicate(current)) {
        count++;
      }
    }
  }

  return count;
}