From edcfbdf4bd9fa43b1c4164e856996e59b3a40749 Mon Sep 17 00:00:00 2001 From: r-paiva Date: Mon, 10 May 2021 21:49:54 +0100 Subject: [PATCH] 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. --- AK/Vector.h | 13 +++++++++++++ Tests/AK/TestVector.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/AK/Vector.h b/AK/Vector.h index 55cf46ca2a7..fd25487ce6e 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -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::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; } diff --git a/Tests/AK/TestVector.cpp b/Tests/AK/TestVector.cpp index 0439a0605fc..673838a3687 100644 --- a/Tests/AK/TestVector.cpp +++ b/Tests/AK/TestVector.cpp @@ -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 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 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 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 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 v { 1, 2, 3, 4, 5 }; + + EXPECT(!v.contains_in_range(2, 2, 4)); +}