Merge pull request #785 from OskarLinde/vector_min_max

Make min() and max() handle vector argument
master
Marius Kintel 2014-05-17 11:59:01 -04:00
commit 7a709b5e8b
3 changed files with 81 additions and 0 deletions

View File

@ -210,6 +210,15 @@ Value builtin_min(const Context *, const EvalContext *evalctx)
size_t n = evalctx->numArgs();
if (n >= 1) {
const Value &v0 = evalctx->getArgValue(0);
if (n == 1 && v0.type() == Value::VECTOR && !v0.toVector().empty()) {
Value min = v0.toVector()[0];
for (int i = 1; i < v0.toVector().size(); i++) {
if (v0.toVector()[i] < min)
min = v0.toVector()[i];
}
return min;
}
if (v0.type() == Value::NUMBER) {
double val = v0.toDouble();
for (size_t i = 1; i < n; ++i) {
@ -234,6 +243,15 @@ Value builtin_max(const Context *, const EvalContext *evalctx)
size_t n = evalctx->numArgs();
if (n >= 1) {
const Value &v0 = evalctx->getArgValue(0);
if (n == 1 && v0.type() == Value::VECTOR && !v0.toVector().empty()) {
Value max = v0.toVector()[0];
for (int i = 1; i < v0.toVector().size(); i++) {
if (v0.toVector()[i] > max)
max = v0.toVector()[i];
}
return max;
}
if (v0.type() == Value::NUMBER) {
double val = v0.toDouble();
for (size_t i = 1; i < n; ++i) {

View File

@ -0,0 +1,33 @@
echo(min());
echo(max());
echo(min([]));
echo(max([]));
echo(min(undef));
echo(max(undef));
echo(min("a"));
echo(max("b"));
echo(min(0));
echo(max(0));
echo(min([0]));
echo(max([0]));
echo(min(0,1));
echo(max(0,1));
echo(min(0,1,2));
echo(max(0,1,2));
echo(min(0,2,1));
echo(max(0,2,1));
echo(min(1,0,2));
echo(max(1,0,2));
echo(min(2,1,0));
echo(max(2,1,0));
echo(min("a","b"));
echo(max("a","b"));
echo(min([0,1,2,3,4,5]));
echo(max([0,1,2,3,4,5]));
echo(min([5,4,3,2,1,0]));
echo(max([5,4,3,2,1,0]));
echo(min([5,4,3,0,1,2]));
echo(max([2,4,3,5,1,0]));
// TODO: What should these do?
//echo(min([[1,2],[3,4]]));
//echo(max([[1,2],[3,4]]));

View File

@ -0,0 +1,30 @@
ECHO: undef
ECHO: undef
ECHO: undef
ECHO: undef
ECHO: undef
ECHO: undef
ECHO: undef
ECHO: undef
ECHO: 0
ECHO: 0
ECHO: 0
ECHO: 0
ECHO: 0
ECHO: 1
ECHO: 0
ECHO: 2
ECHO: 0
ECHO: 2
ECHO: 0
ECHO: 2
ECHO: 0
ECHO: 2
ECHO: undef
ECHO: undef
ECHO: 0
ECHO: 5
ECHO: 0
ECHO: 5
ECHO: 0
ECHO: 5