Add any() and all() methods to Array

These can be used as faster, more convenient shorthands to
using `filter()` + `size()`.
This commit is contained in:
Hugo Locurcio
2021-07-10 20:19:47 +02:00
parent 2ec379e1f9
commit a98e31aa3a
4 changed files with 93 additions and 0 deletions

View File

@@ -501,6 +501,50 @@ Variant Array::reduce(const Callable &p_callable, const Variant &p_accum) const
return ret;
}
bool Array::any(const Callable &p_callable) const {
const Variant *argptrs[1];
for (int i = 0; i < size(); i++) {
argptrs[0] = &get(i);
Variant result;
Callable::CallError ce;
p_callable.call(argptrs, 1, result, ce);
if (ce.error != Callable::CallError::CALL_OK) {
ERR_FAIL_V_MSG(false, "Error calling method from 'any': " + Variant::get_callable_error_text(p_callable, argptrs, 1, ce));
}
if (result.operator bool()) {
// Return as early as possible when one of the conditions is `true`.
// This improves performance compared to relying on `filter(...).size() >= 1`.
return true;
}
}
return false;
}
bool Array::all(const Callable &p_callable) const {
const Variant *argptrs[1];
for (int i = 0; i < size(); i++) {
argptrs[0] = &get(i);
Variant result;
Callable::CallError ce;
p_callable.call(argptrs, 1, result, ce);
if (ce.error != Callable::CallError::CALL_OK) {
ERR_FAIL_V_MSG(false, "Error calling method from 'all': " + Variant::get_callable_error_text(p_callable, argptrs, 1, ce));
}
if (!(result.operator bool())) {
// Return as early as possible when one of the inverted conditions is `false`.
// This improves performance compared to relying on `filter(...).size() >= array_size().`.
return false;
}
}
return true;
}
struct _ArrayVariantSort {
_FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
bool valid = false;