82 |
83 | | Function |
84 | Description |
85 |
86 |
87 | | abs(expression) |
88 | Returns the absolute value of the expression |
89 |
90 |
91 | | sum(expression, ...) |
92 | Returns the sum of all arguments |
93 |
94 |
95 | | floor(expression) |
96 | Rounds the value of the expression down to the nearest integer |
97 |
98 |
99 | | ceil(expression) |
100 | Rounds the value of the expression up to the nearest integer |
101 |
102 |
103 | | round(expression) |
104 | Rounds the value of the expression to the nearest integer in the direction decided by the configured rounding mode |
105 |
106 |
107 | | min(expression, ...) |
108 | Returns the value of the smallest argument |
109 |
110 |
111 | | max(expression, ...) |
112 | Returns the value of the largest argument |
113 |
114 |
115 | | if(condition, trueValue, falseValue) |
116 | Returns trueValue if condition is true(condition != 0), otherwise it returns falseValue |
117 |
118 |
119 |
120 | ### Examples:
121 | ````Kotlin
122 | val result = Expressions()
123 | .eval("(5+5)*10") // returns 100
124 | ````
125 | You can define variables with the `define` method.
126 | ````Kotlin
127 | val result = Expressions()
128 | .define("x", 5)
129 | .eval("x*10") // returns 50
130 | ````
131 | The define method returns the expression instance to allow chaining definition method calls together.
132 | ````Kotlin
133 | val result = Expressions()
134 | .define("x", 5)
135 | .define("y", "5*2")
136 | .eval("x*y") // returns 50
137 | ````
138 | Variable definition expressions can reference previously defined variables.
139 | ````Kotlin
140 | val result = Expressions()
141 | .define("x", 5)
142 | .define("y", "x^2")
143 | .eval("y*x") // returns 125
144 | ````
145 | You can add new functions with the `addFunction` method.
146 | ````kotlin
147 | val result = Expressions()
148 | .addFunction("min") { arguments ->
149 | if (arguments.isEmpty()) throw ExpressionException(
150 | "min requires at least one argument")
151 |
152 | arguments.min()!!
153 | }
154 | .eval("min(4, 8, 16)") // returns 4
155 | ````
156 | You can set the precision and rounding mode with `setPrecision` and `setRoundingMode`.
157 | ````Kotlin
158 | val result = Expressions()
159 | .setPrecision(128)
160 | .setRoundingMode(RoundingMode.UP)
161 | .eval("222^3/5.5")
162 | ````
163 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/keelar/exprk/internal/Scanner.kt:
--------------------------------------------------------------------------------
1 | package com.github.keelar.exprk.internal
2 |
3 | import java.math.MathContext
4 | import com.github.keelar.exprk.ExpressionException
5 | import com.github.keelar.exprk.internal.TokenType.*
6 |
7 | private fun invalidToken(c: Char) {
8 | throw ExpressionException("Invalid token '$c'")
9 | }
10 |
11 | internal class Scanner(private val source: String,
12 | private val mathContext: MathContext) {
13 |
14 | private val tokens: MutableList