mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2025-01-22 17:24:48 -05: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
Notes:
sideshowbarker
2024-07-18 04:46:13 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/commit/1a71e20f93c
1 changed files with 10 additions and 0 deletions
10
AK/HashMap.h
10
AK/HashMap.h
|
@ -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;
|
||||
|
|
Loading…
Reference in a new issue