Skip to content

Commit 11f73c6

Browse files
author
Igor Urisman
committed
WIP
1 parent 1d44b7a commit 11f73c6

File tree

1 file changed

+33
-14
lines changed

1 file changed

+33
-14
lines changed

src/main/java/com/variant/spi/stdlib/hook/WeightedRandomTargetingHook.java

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.variant.server.spi.TargetingLifecycleEvent;
44
import com.variant.server.spi.TargetingLifecycleHook;
5+
import com.variant.share.error.VariantException;
56
import com.variant.share.schema.State;
67
import com.variant.share.schema.Variation;
78
import com.variant.share.yaml.YamlMap;
@@ -36,21 +37,36 @@
3637
*/
3738
public class WeightedRandomTargetingHook implements TargetingLifecycleHook {
3839

39-
final private String propName;
40+
private String propName = "weight";
4041

41-
public WeightedRandomTargetingHook() {
42-
propName = "weight";
43-
}
44-
public WeightedRandomTargetingHook(YamlNode<?> node) {
45-
var valOpt = Optional.ofNullable(((YamlMap) node).value().get("key"));
46-
propName = valOpt
47-
.map(scalar -> ((YamlScalar<String>)scalar).value())
48-
.orElseThrow(
49-
() ->
50-
new RuntimeException(
51-
"Unable to value [%s] to a string literal"
52-
.formatted("foo"))
42+
public WeightedRandomTargetingHook(YamlNode<?> init) {
43+
Optional.ofNullable(init)
44+
.ifPresentOrElse (
45+
node -> {
46+
if (node instanceof YamlMap mapNode) {
47+
propName = Optional.ofNullable(mapNode.value().get("key"))
48+
.map(
49+
valueNode -> {
50+
if (valueNode instanceof YamlScalar<?> scalarNode && scalarNode.value() instanceof String string) {
51+
return string;
52+
} else {
53+
throw new VariantException(
54+
"Unable to value [%s] to a string literal".formatted(valueNode));
55+
}
56+
}
57+
)
58+
.orElseThrow(
59+
() -> new VariantException(
60+
"Required key 'key' not found in the initializer map"));
61+
}
62+
else {
63+
throw new VariantException("The hook initializer must be a YAML map");
64+
}
65+
},
66+
// No init key was given
67+
() -> propName = "weight"
5368
);
69+
5470
}
5571
private static Random rand = new Random();
5672

@@ -67,7 +83,10 @@ public Optional<Variation.Experience> post(TargetingLifecycleEvent event) {
6783
String.format("No experiences in variation [%s] are defined on state [%s]", var.getName(), state.getName()));
6884
}
6985
double weightSum = definedExperiences.stream()
70-
.map(e -> Double.parseDouble(e.getParameters().get(propName)))
86+
.map(e -> {
87+
var val = e.getParameters().get(propName);
88+
return Double.parseDouble(e.getParameters().get(propName));
89+
})
7190
.reduce(0D, Double::sum);
7291

7392
double randVal = rand.nextDouble() * weightSum;

0 commit comments

Comments
 (0)