leastOccurrences method

(bool, int)? leastOccurrences()

Finds the least common value in the list.

Returns a record (tuple) containing the least common value and its frequency. If the list is empty, returns null.

Implementation

(bool, int)? leastOccurrences() {
  // check if the list is empty before calling reduce
  if (isEmpty) {
    return null;
  }

  // Create a new HashMap to store each boolean and its frequency.
  final HashMap<bool, int> frequencyMap = HashMap<bool, int>();
  // Iterate over each boolean in the list.
  for (final bool item in this) {
    // Update the frequency of the current boolean in the map, or
    // set it to 1 if it's not in the map yet.
    frequencyMap.update(item, (int value) => value + 1, ifAbsent: () => 1);
  }

  // Find the key-value pair with the lowest value (frequency) in the map.
  final MapEntry<bool, int> leastCommonEntry = frequencyMap.entries.reduce(
    (MapEntry<bool, int> a, MapEntry<bool, int> b) => a.value < b.value ? a : b,
  );

  // Return a tuple with the least common value and its frequency.
  return (leastCommonEntry.key, leastCommonEntry.value);
}