diff --git a/AK/HashMap.h b/AK/HashMap.h index 8a7d2f3160e..e5da64c1b60 100644 --- a/AK/HashMap.h +++ b/AK/HashMap.h @@ -75,14 +75,18 @@ public: } template - void remove_all_matching(TUnaryPredicate predicate) + bool remove_all_matching(TUnaryPredicate predicate) { + bool something_was_removed = false; for (auto it = begin(); it != end();) { - if (predicate(it->key, it->value)) + if (predicate(it->key, it->value)) { it = remove(it); - else + something_was_removed = true; + } else { ++it; + } } + return something_was_removed; } using HashTableType = HashTable; diff --git a/AK/HashTable.h b/AK/HashTable.h index bb4d08e3412..fbe47a0cf7e 100644 --- a/AK/HashTable.h +++ b/AK/HashTable.h @@ -419,14 +419,18 @@ public: } template - void remove_all_matching(TUnaryPredicate predicate) + bool remove_all_matching(TUnaryPredicate predicate) { + bool something_was_removed = false; for (auto it = begin(); it != end();) { - if (predicate(*it)) + if (predicate(*it)) { it = remove(it); - else + something_was_removed = true; + } else { ++it; + } } + return something_was_removed; } private: diff --git a/Tests/AK/TestHashMap.cpp b/Tests/AK/TestHashMap.cpp index 9fef97d8e95..b04ab35f328 100644 --- a/Tests/AK/TestHashMap.cpp +++ b/Tests/AK/TestHashMap.cpp @@ -82,17 +82,18 @@ TEST_CASE(remove_all_matching) EXPECT_EQ(map.size(), 4u); - map.remove_all_matching([&](int key, String const& value) { - return key == 1 || value == "Two"; - }); + EXPECT_EQ(map.remove_all_matching([&](int key, String const& value) { return key == 1 || value == "Two"; }), true); EXPECT_EQ(map.size(), 2u); EXPECT(map.contains(3)); EXPECT(map.contains(4)); - map.remove_all_matching([&](int, String const&) { return true; }); + EXPECT_EQ(map.remove_all_matching([&](int, String const&) { return true; }), true); + EXPECT_EQ(map.remove_all_matching([&](int, String const&) { return false; }), false); EXPECT(map.is_empty()); + + EXPECT_EQ(map.remove_all_matching([&](int, String const&) { return true; }), false); } TEST_CASE(case_insensitive) diff --git a/Tests/AK/TestHashTable.cpp b/Tests/AK/TestHashTable.cpp index a5eb34d97c3..40dd457aa5b 100644 --- a/Tests/AK/TestHashTable.cpp +++ b/Tests/AK/TestHashTable.cpp @@ -95,13 +95,16 @@ TEST_CASE(table_remove_all_matching) EXPECT_EQ(ints.size(), 4u); - ints.remove_all_matching([&](int value) { return value > 2; }); + EXPECT_EQ(ints.remove_all_matching([&](int value) { return value > 2; }), true); + EXPECT_EQ(ints.remove_all_matching([&](int) { return false; }), false); EXPECT_EQ(ints.size(), 2u); - ints.remove_all_matching([&](int) { return true; }); + EXPECT_EQ(ints.remove_all_matching([&](int) { return true; }), true); EXPECT(ints.is_empty()); + + EXPECT_EQ(ints.remove_all_matching([&](int) { return true; }), false); } TEST_CASE(case_insensitive)