From 1a71e20f93ceb113b067174e3a94124143d178d1 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 4 Sep 2021 17:27:59 +0200 Subject: [PATCH] AK: Add HashMap::ensure(key, callback) This function ensures that a key is present in the HashMap. If it's not present, it is inserted, and the corresponding value is initialized with whatever the callback returns. It allows us to express this: auto it = map.find(key); if (it == map.end()) { map.set(it, make_a_value()); it = map.find(key); } auto& value = it->value; Like this: auto& value = map.ensure(key, [] { return make_a_value(); }); Note that the callback is only invoked if we have to insert a missing key into the HashMap. This is important in case constructing the default value is expensive or otherwise undesirable. --- AK/HashMap.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/AK/HashMap.h b/AK/HashMap.h index e5e9bb66fd..3eb103abdd 100644 --- a/AK/HashMap.h +++ b/AK/HashMap.h @@ -139,6 +139,16 @@ public: return find(key)->value; } + template + V& ensure(K const& key, Callback initialization_callback) + { + auto it = find(key); + if (it == end()) { + set(key, initialization_callback()); + } + return find(key)->value; + } + [[nodiscard]] Vector keys() const { Vector list;