mostOccurrences method
Returns a MapEntry with the most common value and its frequency,
or null if the iterable is empty.
Dart's type system doesn’t allow us to return a strongly typed enum from a method that works with the base Enum type. This is because Dart's generics are invariant, which means you can’t use a subtype (like ZodiacSigns) where a base type (like Enum) is expected.
Implementation
@useResult
MapEntry<Enum, int>? mostOccurrences() {
if (isEmpty) {
return null;
}
final Map<Enum, int> frequencyMap = <Enum, int>{};
for (final Enum item in this) {
// Map.update is called for in-place mutation; no Future is involved
// ignore: require_future_error_handling
frequencyMap.update(item, (int value) => value + 1, ifAbsent: () => 1);
}
// The map is guaranteed non-empty since we checked isEmpty above.
MapEntry<Enum, int>? mostCommonEntry;
for (final MapEntry<Enum, int> entry in frequencyMap.entries) {
if (mostCommonEntry == null || entry.value > mostCommonEntry.value) {
mostCommonEntry = entry;
}
}
return mostCommonEntry;
}