Skip to content

Instantly share code, notes, and snippets.

@saliouseck2009
Created April 20, 2022 07:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saliouseck2009/74b506ba9b5ea1fbfd048a523e6e3c35 to your computer and use it in GitHub Desktop.
Save saliouseck2009/74b506ba9b5ea1fbfd048a523e6e3c35 to your computer and use it in GitHub Desktop.
update map
//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