[muscript] OEnum for representing enums

This commit is contained in:
Johannes Frohnmeyer 2022-06-04 18:35:27 +02:00
parent 47c30f499b
commit 340e93d6d4
Signed by: Johannes
GPG Key ID: E76429612C2929F4

View File

@ -0,0 +1,52 @@
package io.gitlab.jfronny.muscript.optic;
import java.util.*;
/** An enum represented as an OObject with automatic conversions to a number (index) and string (selected value) */
public record OEnum(Map<String, OAny<?>> values, OEnumEntry value) implements OObject {
public OEnum(List<String> values, String value) {
this(createMap(values, value), new OEnumEntry(value, values.indexOf(value), true));
}
@Override
public Map<String, OAny<?>> getValue() {
return values;
}
@Override
public OString asString() {
return value;
}
@Override
public ONumber asNumber() {
return value.asNumber();
}
private static Map<String, OAny<?>> createMap(List<String> values, String value) {
Map<String, OAny<?>> result = new LinkedHashMap<>();
OEnumEntry v = new OEnumEntry(value, values.indexOf(value), true);
result.put("value", v);
for (int i = 0; i < values.size(); i++) {
result.put(values.get(i), new OEnumEntry(values.get(i), i, values.get(i).equals(value)));
}
return Map.copyOf(result);
}
public record OEnumEntry(String value, int index, boolean selected) implements OString {
@Override
public String getValue() {
return value;
}
@Override
public ONumber asNumber() {
return OFinal.of(index);
}
@Override
public OBool asBool() {
return OFinal.of(selected);
}
}
}