leastOccurrences method

  1. @useResult
Occurrence<T>? leastOccurrences()

Returns an Occurrence of the least common value and its frequency, or null if the iterable is empty.

Implementation

@useResult
Occurrence<T>? leastOccurrences() {
  if (isEmpty) {
    return null;
  }

  // Create a new HashMap to store each integer and its frequency.
  final HashMap<T, int> frequencyMap = HashMap<T, int>();

  // Iterate over each integer in the list.
  for (final T item in this) {
    // Update the frequency of the current integer in the map,
    // or set it to 1 if it's not in the map yet.
    // ignore: require_future_error_handling -- update is synchronous; no future to handle
    frequencyMap.update(item, (int value) => value + 1, ifAbsent: () => 1);
  }

  // Find and return the key with the lowest value (frequency) in the map.
  final MapEntry<T, int>? leastCommonEntry = frequencyMap.entries.fold(
    null,
    (MapEntry<T, int>? previous, MapEntry<T, int> element) =>
        previous == null || element.value < previous.value ? element : previous,
  );

  if (leastCommonEntry == null) {
    return null;
  }

  return Occurrence<T>(leastCommonEntry.key, leastCommonEntry.value);
}