Skip to content

Commit

Permalink
Fixed errors when converting island levels to worth values as well as…
Browse files Browse the repository at this point in the history
… optimizing it
  • Loading branch information
OmerBenGera committed Feb 4, 2022
1 parent 4506339 commit 04a1715
Showing 1 changed file with 33 additions and 4 deletions.
Expand Up @@ -10,6 +10,7 @@
import com.bgsoftware.superiorskyblock.utils.debug.PluginDebugger;
import com.bgsoftware.superiorskyblock.values.container.BlockValuesContainer;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
Expand All @@ -24,6 +25,23 @@

public final class BlockValuesHandler extends AbstractHandler implements BlockValuesManager {

private static final Map<String, BigDecimal> CACHED_BIG_DECIMALS;

static {
ImmutableMap.Builder<String, BigDecimal> mapBuilder = new ImmutableMap.Builder<>();
mapBuilder.put("", BigDecimal.ZERO);

for (int i = 0; i <= 10; ++i) {
mapBuilder.put(i + "", BigDecimal.valueOf(i));
if (i != 0) {
mapBuilder.put((i * 100) + "", BigDecimal.valueOf(i * 100));
mapBuilder.put((i * 1000) + "", BigDecimal.valueOf(i * 1000));
}
}

CACHED_BIG_DECIMALS = mapBuilder.build();
}

private static final Bindings bindings = createBindings();

private static final KeyMap<CustomKeyParser> customKeyParsers = new KeyMap<>();
Expand Down Expand Up @@ -231,15 +249,22 @@ public Key convertKey(Key original) {
}

public BigDecimal convertValueToLevel(BigDecimal value) {
// If the formula contains no mathematical operations or the placeholder for the worth value,
// we can directly create the BigDecimal instance from it.
try {
return fastBigDecimalFromString(plugin.getSettings().getIslandLevelFormula());
} catch (NumberFormatException ignored) {
}

try {
Object obj = plugin.getScriptEngine().eval(plugin.getSettings().getIslandLevelFormula()
Object evaluated = plugin.getScriptEngine().eval(plugin.getSettings().getIslandLevelFormula()
.replace("{}", value.toString()), bindings);

// Checking for division by 0
if (obj.equals(Double.POSITIVE_INFINITY) || obj.equals(Double.NEGATIVE_INFINITY))
obj = 0D;
if (evaluated.equals(Double.POSITIVE_INFINITY) || evaluated.equals(Double.NEGATIVE_INFINITY))
return BigDecimal.ZERO;

return new BigDecimal(obj.toString());
return fastBigDecimalFromString(evaluated.toString());
} catch (ScriptException ex) {
ex.printStackTrace();
PluginDebugger.debug(ex);
Expand All @@ -255,4 +280,8 @@ private void convertValuesToLevels() {
}
}

private static BigDecimal fastBigDecimalFromString(String value) {
return CACHED_BIG_DECIMALS.getOrDefault(value, new BigDecimal(value));
}

}

0 comments on commit 04a1715

Please sign in to comment.