From 819f099a8eb595689bc37933c10d2a4fdb7737b1 Mon Sep 17 00:00:00 2001 From: Luke Date: Sat, 21 Nov 2020 18:12:35 +0000 Subject: [PATCH] AK: Add first_matching and last_matching to Vector first_matching returns the first item in the vector that matches the given condition. last_matching returns the last item in the vector that matches the given condition. --- AK/Vector.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/AK/Vector.h b/AK/Vector.h index c6c880e901..b58775922c 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -336,6 +336,28 @@ public: m_size += other.m_size; } + template + Optional first_matching(Callback callback) + { + for (size_t i = 0; i < size(); ++i) { + if (callback(at(i))) { + return at(i); + } + } + return {}; + } + + template + Optional last_matching(Callback callback) + { + for (ssize_t i = size() - 1; i >= 0; --i) { + if (callback(at(i))) { + return at(i); + } + } + return {}; + } + template bool remove_first_matching(Callback callback) {