Created
September 26, 2025 18:14
-
-
Save emmanuelrosa/2352fc7c0f58678af4fe217812b1c6a6 to your computer and use it in GitHub Desktop.
Exercise: Restaurant ratings (a weird outcome)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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