Skip to content

Commit 9369224

Browse files
IdanHotrflynn89
authored andcommitted
AK: Implement take_all_matching(predicate) API in HashMap
1 parent 5097e72 commit 9369224

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

AK/HashMap.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,14 @@ class HashMap {
9999
});
100100
}
101101

102+
template<typename TUnaryPredicate>
103+
Vector<Entry> take_all_matching(TUnaryPredicate const& predicate)
104+
{
105+
return m_table.take_all_matching([&](auto& entry) {
106+
return predicate(entry.key, entry.value);
107+
});
108+
}
109+
102110
using HashTableType = HashTable<Entry, EntryTraits, IsOrdered>;
103111
using IteratorType = typename HashTableType::Iterator;
104112
using ConstIteratorType = typename HashTableType::ConstIterator;

Tests/AK/TestHashMap.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,46 @@ TEST_CASE(remove_all_matching)
100100
EXPECT_EQ(map.remove_all_matching([&](int, ByteString const&) { return true; }), false);
101101
}
102102

103+
TEST_CASE(take_all_matching)
104+
{
105+
HashMap<int, ByteString> map;
106+
107+
map.set(1, "One");
108+
map.set(2, "Two");
109+
map.set(3, "Three");
110+
map.set(4, "Four");
111+
112+
EXPECT_EQ(map.size(), 4u);
113+
114+
auto first_entries = map.take_all_matching([&](int key, ByteString const& value) { return key == 1 || value == "Two"; });
115+
EXPECT_EQ(first_entries.size(), 2u);
116+
auto first_low_index = first_entries[0].key > first_entries[1].key ? 1 : 0;
117+
EXPECT_EQ(first_entries[first_low_index].key, 1);
118+
EXPECT_EQ(first_entries[first_low_index].value, "One");
119+
EXPECT_EQ(first_entries[1 - first_low_index].key, 2);
120+
EXPECT_EQ(first_entries[1 - first_low_index].value, "Two");
121+
EXPECT_EQ(map.size(), 2u);
122+
123+
EXPECT(map.take_all_matching([&](int, ByteString const&) { return false; }).is_empty());
124+
EXPECT_EQ(map.size(), 2u);
125+
126+
EXPECT(map.contains(3));
127+
EXPECT(map.contains(4));
128+
129+
auto second_entries = map.take_all_matching([&](int, ByteString const&) { return true; });
130+
EXPECT_EQ(second_entries.size(), 2u);
131+
auto second_low_index = second_entries[0].key > second_entries[1].key ? 1 : 0;
132+
EXPECT_EQ(second_entries[second_low_index].key, 3);
133+
EXPECT_EQ(second_entries[second_low_index].value, "Three");
134+
EXPECT_EQ(second_entries[1 - second_low_index].key, 4);
135+
EXPECT_EQ(second_entries[1 - second_low_index].value, "Four");
136+
EXPECT(map.take_all_matching([&](int, ByteString const&) { return false; }).is_empty());
137+
138+
EXPECT(map.is_empty());
139+
140+
EXPECT(map.take_all_matching([&](int, ByteString const&) { return true; }).is_empty());
141+
}
142+
103143
TEST_CASE(case_insensitive)
104144
{
105145
HashMap<ByteString, int, CaseInsensitiveStringTraits> casemap;

0 commit comments

Comments
 (0)