Returns a minimum or maximum item. @param min compute minimum or maximum @param qc query context @return resulting item or Empty#VALUE @throws QueryException query exception
(final boolean min, final QueryContext qc)
| 40 | * @throws QueryException query exception |
| 41 | */ |
| 42 | final Item minmax(final boolean min, final QueryContext qc) throws QueryException { |
| 43 | final Expr values = arg(0); |
| 44 | final Collation collation = toCollation(arg(1), qc); |
| 45 | |
| 46 | if(values instanceof Range) { |
| 47 | final Value value = values.value(qc); |
| 48 | return value.isEmpty() ? Empty.VALUE : value.itemAt(min ? 0 : value.size() - 1); |
| 49 | } |
| 50 | |
| 51 | final Iter iter = values.atomIter(qc, info); |
| 52 | Item item = iter.next(); |
| 53 | if(item == null) return Empty.VALUE; |
| 54 | |
| 55 | final Type type = item.type; |
| 56 | final boolean string = item instanceof AStr; |
| 57 | final boolean dateTime = item instanceof Dtm, duration = item instanceof Dur; |
| 58 | final boolean numeric = !(string || dateTime || duration || type == BOOLEAN || type == QNAME || |
| 59 | item instanceof ADate || item instanceof Dur || item instanceof Bin); |
| 60 | if(numeric) { |
| 61 | if(type.isUntyped()) item = DOUBLE.cast(item, qc, info); |
| 62 | if(item == Dbl.NAN || item == Flt.NAN) return item; |
| 63 | } |
| 64 | for(Item it; (it = qc.next(iter)) != null;) { |
| 65 | final Type type2 = it.type; |
| 66 | if(numeric) { |
| 67 | if(type2.isUntyped()) it = DOUBLE.cast(it, qc, info); |
| 68 | if(it == Dbl.NAN || it == Flt.NAN) return it; |
| 69 | } |
| 70 | if(!(numeric ? it instanceof ANum : string ? it instanceof AStr : |
| 71 | dateTime ? it instanceof Dtm : duration ? it instanceof Dur : type == type2)) { |
| 72 | throw ARGTYPE_X_X_X.get(info, type, type2, it); |
| 73 | } |
| 74 | if(min ^ item.compare(it, collation, true, info) < 0) item = it; |
| 75 | } |
| 76 | return item; |
| 77 | } |
| 78 | |
| 79 | @Override |
| 80 | protected void simplifyArgs(final CompileContext cc) throws QueryException { |