AK: Added contains_in_range to Vector

Vector::contains_in_range() allows the search of an element in a given
range on a vector object.
Also added testcases for the new Vector method.
This commit is contained in:
r-paiva 2021-05-10 21:49:54 +01:00 committed by Andreas Kling
parent 68de9008e7
commit edcfbdf4bd
Notes: sideshowbarker 2024-07-18 17:40:18 +09:00
2 changed files with 53 additions and 0 deletions

View File

@ -150,6 +150,19 @@ public:
return false;
}
bool contains_in_range(const T& value, const size_t start, const size_t end) const
{
VERIFY(start <= end);
VERIFY(end < size());
for (size_t i = start; i <= end; ++i) {
if (Traits<T>::equals(at(i), value))
return true;
}
return false;
}
// NOTE: Vector::is_null() exists for the benefit of String::copy().
bool is_null() const { return false; }
bool is_empty() const { return size() == 0; }
ALWAYS_INLINE size_t size() const { return m_size; }
size_t capacity() const { return m_capacity; }

View File

@ -399,3 +399,43 @@ TEST_CASE(should_find_index)
EXPECT_EQ(4u, v.find_first_index(0).value());
EXPECT(!v.find_first_index(42).has_value());
}
TEST_CASE(should_contain_start)
{
// Tests whether value is found if at the start of the range.
Vector<int> v { 1, 2, 3, 4, 5 };
EXPECT(v.contains_in_range(1, 0, 4));
}
TEST_CASE(should_contain_end)
{
// Tests whether value is found if at the end of the range.
Vector<int> v { 1, 2, 3, 4, 5 };
EXPECT(v.contains_in_range(5, 0, 4));
}
TEST_CASE(should_contain_range)
{
// Tests whether value is found within a range.
Vector<int> v { 1, 2, 3, 4, 5 };
EXPECT(v.contains_in_range(3, 0, 4));
}
TEST_CASE(should_not_contain_not_present)
{
// Tests whether a value that is not present is not found, as expected.
Vector<int> v { 1, 2, 3, 4, 5 };
EXPECT(!v.contains_in_range(6, 0, 4));
}
TEST_CASE(should_not_contain_present_not_in_range)
{
// Tests whether a value that is present, but not in range, is not found.
Vector<int> v { 1, 2, 3, 4, 5 };
EXPECT(!v.contains_in_range(2, 2, 4));
}