From 2cf4781d147acd51c4b9d35de494cdac79780e5b Mon Sep 17 00:00:00 2001 From: Lenny Maiorani Date: Thu, 24 Jun 2021 10:24:13 -0600 Subject: [PATCH] AK: Reimplement all_of in terms of find_if Problem: - Now that a generic free-function form of `find_if` is implemented the code in `all_of` is redundant. Solution: - Follow the "don't repeat yourself" mantra and make the code DRY by implementing `all_of` in terms of `find_if`. - One tricky part is that since captures are not permitted in `constexpr` lambdas, the lambda created to negate the predicate needs to be created by a function which does not capture and takes the predicate at run-time instead. This allows `all_of` to continue to work in a `constexpr` context. --- AK/AllOf.h | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/AK/AllOf.h b/AK/AllOf.h index a551046b977..603f293425e 100644 --- a/AK/AllOf.h +++ b/AK/AllOf.h @@ -7,6 +7,7 @@ #pragma once #include +#include #include namespace AK { @@ -17,22 +18,16 @@ constexpr bool all_of( TEndIterator const& end, auto const& predicate) { - for (auto iter = begin; iter != end; ++iter) { - if (!predicate(*iter)) { - return false; - } - } - return true; + constexpr auto negated_predicate = [](auto const& pred) { + return [&](auto const& elem) { return !pred(elem); }; + }; + return !(find_if(begin, end, negated_predicate(predicate)) != end); } template constexpr bool all_of(Container&& container, auto const& predicate) { - for (auto&& entry : container) { - if (!predicate(entry)) - return false; - } - return true; + return all_of(container.begin(), container.end(), predicate); } }