Created
April 20, 2022 07:57
-
-
Save saliouseck2009/74b506ba9b5ea1fbfd048a523e6e3c35 to your computer and use it in GitHub Desktop.
update map
This file contains 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
//Set the value if it doesn't | |
//You may be tempted to implement some conditional logic to handle this: | |
class ShoppingCart { | |
final Map<String, int> items = {}; | |
void add(String key, int quantity) { | |
if (items.containsKey(key)) { | |
// item exists: update it | |
items[key] = quantity + items[key]!; | |
} else { | |
// item does not exist: set it | |
items[key] = quantity; | |
} | |
} | |
} | |
//Alternatively, a shorter version would be: | |
class ShoppingCart { | |
final Map<String, int> items = {}; | |
void add(String key, int quantity) { | |
// add 0 if items[key] does not exist | |
items[key] = quantity + (items[key] ?? 0); | |
} | |
} | |
class ShoppingCart { | |
final Map<String, int> items = {}; | |
void add(String key, int quantity) { | |
items.update( | |
key, | |
(value) => quantity + value, | |
ifAbsent: () => quantity, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment