Skip to content

Commit

Permalink
Added random function for math taking min and max arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
0ft3n committed Jan 27, 2024
1 parent 7defdcc commit 6b46ea7
Showing 1 changed file with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.github.benmanes.caffeine.cache.Caffeine
import com.willfp.eco.core.integrations.placeholder.PlaceholderManager
import com.willfp.eco.core.placeholder.context.PlaceholderContext
import com.willfp.eco.internal.placeholder.PlaceholderParser
import com.willfp.eco.util.randDouble
import redempt.crunch.CompiledExpression
import redempt.crunch.Crunch
import redempt.crunch.functional.EvaluationEnvironment
Expand All @@ -22,6 +23,10 @@ private val max = Function("max", 2) {
max(it[0], it[1])
}

private val rand = Function("random", 2) {
randDouble(it[0], it[1])
}

interface ExpressionHandler {
fun evaluate(expression: String, context: PlaceholderContext): Double?
}
Expand Down Expand Up @@ -77,7 +82,7 @@ class ImmediatePlaceholderTranslationExpressionHandler(
.build()

private val env = EvaluationEnvironment().apply {
addFunctions(min, max)
addFunctions(min, max, rand)
}

override fun evaluate(expression: String, context: PlaceholderContext): Double? {
Expand Down Expand Up @@ -106,7 +111,7 @@ class LazyPlaceholderTranslationExpressionHandler(
val compiled = cache.getOrPut(expression) {
val env = EvaluationEnvironment()
env.setVariableNames(*placeholders.toTypedArray())
env.addFunctions(min, max)
env.addFunctions(rand, min, max)
runCatching { Crunch.compileExpression(expression, env) }.getOrNull()
}

Expand Down

0 comments on commit 6b46ea7

Please sign in to comment.