// Challenge: count the frequency of each character in a text.
// Input: "banana"
// Expected output: {b: 1, a: 3, n: 2}
// Solution: we walk through the text and use a Map to keep the count.
// The ?? operator and update help us initialize at 0 the first time.
Map<String, int> countCharacters(String text) {
final counts = <String, int>{};
for (final character in text.split('')) {
// If the character was already there, add 1; otherwise, start at 1.
counts[character] = (counts[character] ?? 0) + 1;
}
return counts;
}
void main() {
print(countCharacters('banana')); // {b: 1, a: 3, n: 2}
print(countCharacters('aabbc')); // {a: 2, b: 2, c: 1}
print(countCharacters('')); // {} (edge case: empty text)
// Explanation:
// We walk through each character. The key to the trick is (counts[character] ?? 0):
// if the key does not exist yet, counts[character] is null, and with ?? 0
// we start at 0 before adding 1. That way we avoid a null error.
}