Skip to content

Instantly share code, notes, and snippets.

@lesnitsky
Created January 10, 2020 12:26
Show Gist options
  • Save lesnitsky/1de49b3dc61dc07325c892f05f7a373e to your computer and use it in GitHub Desktop.
Save lesnitsky/1de49b3dc61dc07325c892f05f7a373e to your computer and use it in GitHub Desktop.
Map<String, int> map = {};
int id = 0;
int getIdOrCreate(String key) {
if (map.containsKey(key)) {
return map[key];
} else {
id++;
map[key] = id;
return id;
}
}
int getIdOrCreate_short(String key) {
return map[key] ??= ++id;
}
void main() {
print(getIdOrCreate('a') == 1);
print(getIdOrCreate('a') == 1);
print(getIdOrCreate_short('b') == 2);
print(getIdOrCreate_short('b') == 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment