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.
This commit is contained in:
Andreas Kling 2021-09-04 17:27:59 +02:00
parent 0094259d72
commit 1a71e20f93

View file

@ -139,6 +139,16 @@ public:
return find(key)->value;
}
template<typename Callback>
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<K> keys() const
{
Vector<K> list;