diff --git a/AK/Vector.h b/AK/Vector.h index cb6a69830a0..3bf34b8d2a6 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -796,6 +796,15 @@ public: return {}; } + template + Optional find_first_index_if(TUnaryPredicate&& finder) const + { + auto maybe_result = AK::find_if(begin(), end(), finder); + if (maybe_result == end()) + return {}; + return maybe_result.index(); + } + void reverse() { for (size_t i = 0; i < size() / 2; ++i) diff --git a/Tests/AK/TestVector.cpp b/Tests/AK/TestVector.cpp index 9e0c5f80674..6bf010b8b7b 100644 --- a/Tests/AK/TestVector.cpp +++ b/Tests/AK/TestVector.cpp @@ -423,6 +423,14 @@ TEST_CASE(should_find_index) EXPECT(!v.find_first_index(42).has_value()); } +TEST_CASE(should_find_predicate_index) +{ + Vector v { 1, 2, 3, 4, 0, 6, 7, 8, 0, 0 }; + + EXPECT_EQ(4u, v.find_first_index_if([](auto const v) { return v == 0; }).value()); + EXPECT(!v.find_first_index_if([](auto const v) { return v == 123; }).has_value()); +} + TEST_CASE(should_contain_start) { // Tests whether value is found if at the start of the range.