Updated/fixed crunch

This commit is contained in:
Auxilor
2022-03-09 11:20:54 +00:00
parent af198d30f7
commit ca9c940b2b
2 changed files with 11 additions and 20 deletions

View File

@@ -2,7 +2,7 @@ group 'com.willfp'
version rootProject.version
dependencies {
implementation 'com.github.Redempt:Crunch:1.0'
implementation 'com.github.Redempt:Crunch:1.1.2'
compileOnly 'net.kyori:adventure-platform-bukkit:4.1.0'
compileOnly 'org.apache.maven:maven-artifact:3.8.1'
compileOnly 'com.google.code.gson:gson:2.8.8'

View File

@@ -1,5 +1,7 @@
package com.willfp.eco.internal.spigot.math
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.Caffeine
import com.willfp.eco.core.integrations.placeholder.PlaceholderManager
import org.bukkit.entity.Player
import redempt.crunch.CompiledExpression
@@ -7,32 +9,21 @@ import redempt.crunch.Crunch
import redempt.crunch.data.FastNumberParsing
import redempt.crunch.functional.EvaluationEnvironment
private val cache = mutableMapOf<String, CompiledExpression>()
private val cache: Cache<String, CompiledExpression> = Caffeine.newBuilder().build()
private val goToZero = Crunch.compileExpression("0")
fun evaluateExpression(expression: String, player: Player?): Double {
val placeholderValues = PlaceholderManager.findPlaceholdersIn(expression)
.map { PlaceholderManager.translatePlaceholders(expression, player) }
.map { PlaceholderManager.translatePlaceholders(it, player) }
.map { runCatching { FastNumberParsing.parseDouble(it) }.getOrDefault(0.0) }
.toDoubleArray()
val compiled = generateExpression(expression)
return runCatching { compiled.evaluate(*placeholderValues) }.getOrDefault(0.0)
}
private fun generateExpression(expression: String): CompiledExpression {
val cached = cache[expression]
if (cached != null) {
return cached
val compiled = cache.get(expression) {
val placeholders = PlaceholderManager.findPlaceholdersIn(it)
val env = EvaluationEnvironment()
env.setVariableNames(*placeholders.toTypedArray())
runCatching { Crunch.compileExpression(expression, env) }.getOrDefault(goToZero)
}
val placeholders = PlaceholderManager.findPlaceholdersIn(expression)
val env = EvaluationEnvironment()
env.setVariableNames(*placeholders.toTypedArray())
val compiled = runCatching { Crunch.compileExpression(expression, env) }.getOrDefault(goToZero)
cache[expression] = compiled
return compiled
return runCatching { compiled.evaluate(*placeholderValues) }.getOrDefault(0.0)
}