|
| 1 | +package org.csstudio.apputil.formula.array; |
| 2 | + |
| 3 | +import org.epics.util.array.ListNumber; |
| 4 | +import org.epics.vtype.VNumber; |
| 5 | +import org.epics.vtype.VNumberArray; |
| 6 | +import org.epics.vtype.VString; |
| 7 | +import org.epics.vtype.VStringArray; |
| 8 | +import org.epics.vtype.VType; |
| 9 | +import org.epics.vtype.VInt; |
| 10 | +import org.epics.vtype.Alarm; |
| 11 | +import org.epics.vtype.Time; |
| 12 | +import org.epics.vtype.Display; |
| 13 | +import org.phoebus.core.vtypes.VTypeHelper; |
| 14 | + |
| 15 | +import java.util.List; |
| 16 | + |
| 17 | +/** |
| 18 | + * Get index of the specified element in the array. |
| 19 | + */ |
| 20 | +public class ArrayIndexFunction extends BaseArrayFunction { |
| 21 | + |
| 22 | + @Override |
| 23 | + public String getName() { |
| 24 | + return "arrayIndex"; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public String getDescription() { |
| 29 | + return "Returns the index of the specified element in the array, -1 if not found."; |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public List<String> getArguments() { |
| 34 | + return List.of("<String | Number> array", "element"); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Get index of the specified element in the array. |
| 39 | + * @param args Arguments, count will match <code>getArgumentCount()</code> |
| 40 | + * @return A {@link VInt} with the index of the element in the array, -1 if not found. If the arguments are not of |
| 41 | + * the supported types, {@link BaseArrayFunction#DEFAULT_NAN_DOUBLE} or {@link BaseArrayFunction#DEFAULT_EMPTY_STRING} |
| 42 | + */ |
| 43 | + @Override |
| 44 | + public VType compute(VType... args) { |
| 45 | + boolean isStringArray = args[0] instanceof VStringArray; |
| 46 | + if (isStringArray && args[1] instanceof VString) { |
| 47 | + VStringArray stringArray = (VStringArray) args[0]; |
| 48 | + VString element = (VString) args[1]; |
| 49 | + List<String> data = stringArray.getData(); |
| 50 | + |
| 51 | + int idx = data.indexOf(element.getValue()); |
| 52 | + return VInt.of(idx, Alarm.none(), Time.now(), Display.none()); |
| 53 | + } |
| 54 | + else if (VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber) { |
| 55 | + VNumberArray numberArray = (VNumberArray) args[0]; |
| 56 | + ListNumber data = numberArray.getData(); |
| 57 | + VNumber element = (VNumber) args[1]; |
| 58 | + double elementValue = element.getValue().doubleValue(); |
| 59 | + |
| 60 | + for (int i = 0; i < data.size(); i++) { |
| 61 | + if (data.getDouble(i) == elementValue) { |
| 62 | + return VInt.of(i, Alarm.none(), Time.now(), Display.none()); |
| 63 | + } |
| 64 | + } |
| 65 | + // return -1 if not found |
| 66 | + return VInt.of(-1, Alarm.none(), Time.now(), Display.none()); |
| 67 | + } |
| 68 | + else { |
| 69 | + return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments