mirror of
https://github.com/SerenityOS/serenity
synced 2024-10-07 00:19:27 +00:00
AK: Add Array::contains_slow() and ::first_index_of(), with tests :^)
This commit is contained in:
parent
955528055c
commit
892470a912
15
AK/Array.h
15
AK/Array.h
|
@ -7,6 +7,7 @@
|
|||
#pragma once
|
||||
|
||||
#include <AK/Iterator.h>
|
||||
#include <AK/Optional.h>
|
||||
#include <AK/Span.h>
|
||||
#include <AK/StdLibExtras.h>
|
||||
#include <AK/TypedTransfer.h>
|
||||
|
@ -119,6 +120,20 @@ struct Array {
|
|||
return value;
|
||||
}
|
||||
|
||||
bool contains_slow(T const& value) const
|
||||
{
|
||||
return first_index_of(value).has_value();
|
||||
}
|
||||
|
||||
Optional<size_t> first_index_of(T const& value) const
|
||||
{
|
||||
for (size_t i = 0; i < Size; ++i) {
|
||||
if (__data[i] == value)
|
||||
return i;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Conditional<Size == 0, Detail::EmptyArrayStorage<T>, T[Size]> __data;
|
||||
};
|
||||
|
||||
|
|
|
@ -28,3 +28,21 @@ TEST_CASE(compile_time_iterable)
|
|||
constexpr Array<int, 8> array = { 0, 1, 2, 3, 4, 5, 6, 7 };
|
||||
static_assert(constexpr_sum(array) == 28);
|
||||
}
|
||||
|
||||
TEST_CASE(contains_slow)
|
||||
{
|
||||
constexpr Array<int, 8> array = { 0, 1, 2, 3, 4, 5, 6, 7 };
|
||||
EXPECT(array.contains_slow(0));
|
||||
EXPECT(array.contains_slow(4));
|
||||
EXPECT(array.contains_slow(7));
|
||||
EXPECT(!array.contains_slow(42));
|
||||
}
|
||||
|
||||
TEST_CASE(first_index_of)
|
||||
{
|
||||
constexpr Array<int, 8> array = { 0, 1, 2, 3, 4, 5, 6, 7 };
|
||||
EXPECT(array.first_index_of(0) == 0u);
|
||||
EXPECT(array.first_index_of(4) == 4u);
|
||||
EXPECT(array.first_index_of(7) == 7u);
|
||||
EXPECT(!array.first_index_of(42).has_value());
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue