Skip to content

Instantly share code, notes, and snippets.

@emmanuelrosa
Created September 26, 2025 18:14
Show Gist options
  • Save emmanuelrosa/2352fc7c0f58678af4fe217812b1c6a6 to your computer and use it in GitHub Desktop.
Save emmanuelrosa/2352fc7c0f58678af4fe217812b1c6a6 to your computer and use it in GitHub Desktop.
Exercise: Restaurant ratings (a weird outcome)
void main() {
var restaurants = [
{
'name': 'Pizza Mario',
'cuisine': 'Italian',
'ratings': [5.0, 3.5, 4.5],
},
{
'name': 'Chez Anne',
'cuisine': 'French',
'ratings': [5.0, 4.5, 4.0],
},
{
'name': 'Navaratna',
'cuisine': 'Indian',
'ratings': [4.0, 4.5, 4.0],
},
];
for (var restaurant in restaurants) {
final ratings = restaurant['ratings'] as List<double>;
// I expected this to update a *copy* of the restaurant Map thinking that 'restaurant' is passed by value. But...
restaurant['avgRating'] = ratings.reduce((a, b) => a + b) / ratings.length;
}
// I printed the original collection here (on accident) and it showed the restaurants with the additional key.
print(restaurants);
/*
* Formatted output.
* [
* {name: Pizza Mario, cuisine: Italian, ratings: [5.0, 3.5, 4.5], avgRating: 4.333333333333333},
* {name: Chez Anne, cuisine: French, ratings: [5.0, 4.5, 4.0], avgRating: 4.5},
* {name: Navaratna, cuisine: Indian, ratings: [4.0, 4.5, 4.0], avgRating: 4.166666666666667}
* ]
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment