Added max() and min() functions to array to return greater or lesser element (or null if data is not of compatible type or empty array). Closes #15697

This commit is contained in:
Juan Linietsky 2018-08-23 15:31:02 -03:00
parent df4dadafb7
commit adc0188d9f
3 changed files with 54 additions and 0 deletions

View file

@ -355,11 +355,58 @@ Variant Array::pop_front() {
return Variant();
}
Variant Array::min() const {
Variant minval;
for (int i = 0; i < size(); i++) {
if (i == 0) {
minval = get(i);
} else {
bool valid;
Variant ret;
Variant test = get(i);
Variant::evaluate(Variant::OP_LESS, test, minval, ret, valid);
if (!valid) {
return Variant(); //not a valid comparison
}
if (bool(ret)) {
//is less
minval = test;
}
}
}
return minval;
}
Variant Array::max() const {
Variant maxval;
for (int i = 0; i < size(); i++) {
if (i == 0) {
maxval = get(i);
} else {
bool valid;
Variant ret;
Variant test = get(i);
Variant::evaluate(Variant::OP_GREATER, test, maxval, ret, valid);
if (!valid) {
return Variant(); //not a valid comparison
}
if (bool(ret)) {
//is less
maxval = test;
}
}
}
return maxval;
}
Array::Array(const Array &p_from) {
_p = NULL;
_ref(p_from);
}
Array::Array() {
_p = memnew(ArrayPrivate);

View file

@ -90,6 +90,9 @@ public:
Array duplicate(bool p_deep = false) const;
Variant min() const;
Variant max() const;
Array(const Array &p_from);
Array();
~Array();

View file

@ -516,6 +516,8 @@ struct _VariantCall {
VCALL_LOCALMEM4R(Array, bsearch_custom);
VCALL_LOCALMEM1R(Array, duplicate);
VCALL_LOCALMEM0(Array, invert);
VCALL_LOCALMEM0R(Array, max);
VCALL_LOCALMEM0R(Array, min);
static void _call_PoolByteArray_get_string_from_ascii(Variant &r_ret, Variant &p_self, const Variant **p_args) {
@ -1705,6 +1707,8 @@ void register_variant_methods() {
ADDFUNC4R(ARRAY, INT, Array, bsearch_custom, NIL, "value", OBJECT, "obj", STRING, "func", BOOL, "before", varray(true));
ADDFUNC0NC(ARRAY, NIL, Array, invert, varray());
ADDFUNC1R(ARRAY, ARRAY, Array, duplicate, BOOL, "deep", varray(false));
ADDFUNC0R(ARRAY, NIL, Array, max, varray());
ADDFUNC0R(ARRAY, NIL, Array, min, varray());
ADDFUNC0R(POOL_BYTE_ARRAY, INT, PoolByteArray, size, varray());
ADDFUNC2(POOL_BYTE_ARRAY, NIL, PoolByteArray, set, INT, "idx", INT, "byte", varray());