mostOccurrences method
Finds the most common value in the list.
Returns a record (tuple) containing the most common value and its frequency. If the list is empty, returns null.
Implementation
(bool, int)? mostOccurrences() {
// 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 highest value (frequency) in the map.
final MapEntry<bool, int> mostCommonEntry = frequencyMap.entries.reduce(
(MapEntry<bool, int> a, MapEntry<bool, int> b) => a.value > b.value ? a : b,
);
// Return a tuple with the most common value and its frequency.
return (mostCommonEntry.key, mostCommonEntry.value);
}