DEnum: add support for omitting selected value and coercion to list
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed

This commit is contained in:
Johannes Frohnmeyer 2023-03-11 12:27:49 +01:00
parent 3d0d3a1595
commit 55fd58bcdf
Signed by: Johannes
GPG Key ID: E76429612C2929F4

View File

@ -1,13 +1,25 @@
package io.gitlab.jfronny.muscript.data.dynamic;
import io.gitlab.jfronny.commons.StringFormatter;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* An enum represented as an OObject with automatic conversions to a number (index) and string (selected value)
* An enum represented as an OObject.
* May also have a selected value with automatic conversions to a number (index) and string
*/
public record DEnum(Map<String, Dynamic<?>> values, DEnumEntry value) implements DObject {
public record DEnum(Map<String, Dynamic<?>> values, @Nullable DEnumEntry value) implements DObject {
public DEnum(Map<String, Dynamic<?>> values) {
this(values, null);
}
public DEnum(List<String> values, String value) {
this(createMap(values, value), new DEnumEntry(value, values.indexOf(value), true));
this(createMap(values, value), value == null ? null : new DEnumEntry(value, values.indexOf(value), true));
}
public DEnum(List<String> values) {
this(values, null);
}
@Override
@ -15,14 +27,19 @@ public record DEnum(Map<String, Dynamic<?>> values, DEnumEntry value) implements
return values;
}
@Override
public DList asList() {
return DFinal.of(List.copyOf(values.values()));
}
@Override
public DString asString() {
return value;
return value != null ? value : DFinal.of(StringFormatter.toString(values));
}
@Override
public DNumber asNumber() {
return value.asNumber();
return value != null ? value.asNumber() : DObject.super.asNumber();
}
private static Map<String, Dynamic<?>> createMap(List<String> values, String value) {