mirror of
https://github.com/SerenityOS/serenity
synced 2024-10-15 04:13:11 +00:00
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:
parent
0094259d72
commit
1a71e20f93
10
AK/HashMap.h
10
AK/HashMap.h
|
@ -139,6 +139,16 @@ public:
|
||||||
return find(key)->value;
|
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
|
[[nodiscard]] Vector<K> keys() const
|
||||||
{
|
{
|
||||||
Vector<K> list;
|
Vector<K> list;
|
||||||
|
|
Loading…
Reference in a new issue