second draft
This commit is contained in:
@@ -34,17 +34,6 @@
|
||||
<version>7.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>${java.fx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>${java.fx.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib</artifactId>
|
||||
@@ -110,30 +99,6 @@
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin> -->
|
||||
<plugin>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>0.0.8</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<!-- Default configuration for running with: mvn clean javafx:run -->
|
||||
<id>default-cli</id>
|
||||
<configuration>
|
||||
<mainClass>ru.darktale.calc.CalcApplication</mainClass>
|
||||
<launcher>app</launcher>
|
||||
<jlinkZipName>app</jlinkZipName>
|
||||
<jlinkImageName>app</jlinkImageName>
|
||||
<noManPages>true</noManPages>
|
||||
<stripDebug>true</stripDebug>
|
||||
<noHeaderFiles>true</noHeaderFiles>
|
||||
<jvmArgs>
|
||||
--add-modules=javafx.controls,javafx.fxml
|
||||
--module-path "C:\Users\mi\.m2\repository\org\openjfx\javafx-fxml\21-ea+24";"C:\Users\mi\.m2\repository\org\openjfx\javafx-controls\21-ea+24";"C:\Users\mi\.m2\repository\org\openjfx\javafx-graphics\21-ea+24";"C:\Users\mi\.m2\repository\org\openjfx\javafx-base\21-ea+24"
|
||||
</jvmArgs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
|
||||
@@ -1,47 +1,33 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import com.google.inject.Guice
|
||||
import javafx.application.Application
|
||||
import javafx.fxml.FXMLLoader
|
||||
import javafx.scene.Scene
|
||||
import javafx.stage.Stage
|
||||
import ru.darktale.calc.infra.BasicModule
|
||||
import ru.darktale.calc.infra.CalculationsModule
|
||||
import ru.darktale.calc.service.KeyEventHandler
|
||||
import ru.darktale.calc.guice.CalculationsModule
|
||||
import ru.darktale.calc.parse.ParseException
|
||||
import ru.darktale.calc.parse.Parser
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import kotlin.system.measureTimeMillis
|
||||
|
||||
|
||||
class CalcApplication : Application() {
|
||||
override fun start(stage: Stage) {
|
||||
initScene(stage)
|
||||
stage.title = "Calc!"
|
||||
stage.show()
|
||||
}
|
||||
|
||||
private fun initScene(stage: Stage) {
|
||||
val injector = Guice.createInjector(BasicModule())
|
||||
val fxmlLoader = FXMLLoader(CalcApplication::class.java.getResource("hello-view.fxml"))
|
||||
fxmlLoader.setControllerFactory { injector.getInstance(it) }
|
||||
val scene = Scene(fxmlLoader.load(), 320.0, 240.0)
|
||||
scene.onKeyPressed = injector.getInstance(KeyEventHandler::class.java)
|
||||
stage.scene = scene
|
||||
}
|
||||
}
|
||||
/*
|
||||
fun main() {
|
||||
Application.launch(CalcApplication::class.java)
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
fun main() {
|
||||
val injector = Guice.createInjector(CalculationsModule())
|
||||
val parser = injector.getInstance(Parser::class.java)
|
||||
val calculator = injector.getInstance(Calculator::class.java)
|
||||
|
||||
val expression = "(3+1)!"
|
||||
val reader = BufferedReader(InputStreamReader(System.`in`))
|
||||
while (true) {
|
||||
val expression = reader.readLine()
|
||||
if (expression == "exit") break
|
||||
val time = measureTimeMillis {
|
||||
try {
|
||||
println("$expression = ${calculator.calculate(parser.parse(expression))}")
|
||||
} catch (ex: CalculationException) {
|
||||
println("Calculation exception ${ex.message}")
|
||||
} catch (ex: ParseException) {
|
||||
println("""${ex.position?.let { " ".repeat(it) + "^" } ?: "parse exception: "}
|
||||
|${ex.message}""".trimMargin())
|
||||
}
|
||||
}
|
||||
println("$time ms elapsed")
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import jakarta.inject.Inject
|
||||
import jakarta.inject.Singleton
|
||||
import javafx.fxml.FXML
|
||||
import javafx.scene.control.TextField
|
||||
import ru.darktale.calc.service.CalculatorService
|
||||
|
||||
@Singleton
|
||||
class CalcController {
|
||||
|
||||
@Inject
|
||||
private lateinit var calculatorService: CalculatorService
|
||||
|
||||
@FXML
|
||||
private lateinit var calcField: TextField
|
||||
|
||||
@FXML
|
||||
private fun on1Click() = addSymbol('1')
|
||||
@FXML
|
||||
private fun on2Click() = addSymbol('2')
|
||||
@FXML
|
||||
private fun on3Click() = addSymbol('3')
|
||||
@FXML
|
||||
private fun on4Click() = addSymbol('4')
|
||||
@FXML
|
||||
private fun on5Click() = addSymbol('5')
|
||||
@FXML
|
||||
private fun on6Click() = addSymbol('6')
|
||||
@FXML
|
||||
private fun on7Click() = addSymbol('7')
|
||||
@FXML
|
||||
private fun on8Click() = addSymbol('8')
|
||||
@FXML
|
||||
private fun on9Click() = addSymbol('9')
|
||||
@FXML
|
||||
private fun on0Click() = addSymbol('0')
|
||||
@FXML
|
||||
private fun onDotClick() = addSymbol('.')
|
||||
|
||||
fun addSymbol(symbol: Char) {
|
||||
println(this)
|
||||
calcField.text = calculatorService.addSymbol(symbol)
|
||||
}
|
||||
|
||||
fun removeLast() {
|
||||
println(this)
|
||||
calcField.text = calculatorService.removeLast()
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import jakarta.inject.Inject
|
||||
import ru.darktale.calc.model.*
|
||||
import ru.darktale.calc.operation.BinaryOperationCalculation
|
||||
import ru.darktale.calc.operation.UnaryOperationCalculation
|
||||
import java.math.BigDecimal
|
||||
import kotlin.collections.ArrayDeque
|
||||
|
||||
@@ -10,8 +13,8 @@ interface Calculator {
|
||||
|
||||
class CalculatorImpl @Inject constructor(
|
||||
private val converter: ExpressionToRplConverter,
|
||||
private val unaryFunctions: Map<UnaryOperation, UnaryOperationFunction<out UnaryOperation>>,
|
||||
private val binaryFunctions: Map<BinaryOperation, BinaryOperationFunction<out BinaryOperation>>,
|
||||
private val unaryFunctions: Map<UnaryOperation, UnaryOperationCalculation<out UnaryOperation>>,
|
||||
private val binaryFunctions: Map<BinaryOperation, BinaryOperationCalculation<out BinaryOperation>>,
|
||||
) : Calculator {
|
||||
|
||||
override fun calculate(expression: Expression): BigDecimal {
|
||||
@@ -25,6 +28,8 @@ class CalculatorImpl @Inject constructor(
|
||||
private fun List<CalculationToken>.process(operands: ArrayDeque<Operand>) = forEach {
|
||||
when (it) {
|
||||
is Operand -> operands.addFirst(it)
|
||||
// else -> with(calculations[it]!!) { operands.calc() }
|
||||
|
||||
is BinaryOperation -> {
|
||||
val second = operands.removeFirst()
|
||||
operands.addFirst(binaryFunctions[it]!!.apply(operands.removeFirst(), second))
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import ru.darktale.calc.model.*
|
||||
import ru.darktale.calc.model.TokenType.*
|
||||
|
||||
interface ExpressionToRplConverter {
|
||||
fun convert(expression: Expression): List<CalculationToken>
|
||||
}
|
||||
@@ -9,41 +12,40 @@ class ExpressionToRplConverterImpl : ExpressionToRplConverter {
|
||||
|
||||
/** RPL - reverse polish notation */
|
||||
private fun Expression.toRpl() = mutableListOf<CalculationToken>().apply {
|
||||
val operationStack = ArrayDeque<ExpressionElement>()
|
||||
val operationStack = ArrayDeque<ExpressionToken>()
|
||||
val queue = ArrayDeque(elements)
|
||||
|
||||
while (queue.isNotEmpty()) {
|
||||
when (val element = queue.removeFirst()) {
|
||||
is Operand -> {
|
||||
this += element
|
||||
if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation
|
||||
}
|
||||
|
||||
is Expression -> queue.addAll(0, element.elements)
|
||||
OpenBracket -> operationStack.addFirst(element)
|
||||
is UnaryOperation -> {
|
||||
if (element.isPrefix) operationStack.addFirst(element)
|
||||
else this += element
|
||||
}
|
||||
|
||||
CloseBracket -> {
|
||||
val element = queue.removeFirst()
|
||||
when (element.tokenType) {
|
||||
EXPRESSION -> queue.addAll(0, (element as Expression).elements)
|
||||
PREFIX_UNARY_OPERATION, PREFIX_FUNCTION -> operationStack.addFirst(element)
|
||||
POSTFIX_UNARY_OPERATION -> this += (element as UnaryOperation)
|
||||
OPEN_BRACKET -> operationStack.addFirst(element)
|
||||
CLOSE_BRACKET -> {
|
||||
// pass elements to RPL
|
||||
while (operationStack.first() != OpenBracket) this += operationStack.removeFirst() as CalculationToken
|
||||
//remove OpenBracket itself
|
||||
operationStack.removeFirst()
|
||||
if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation
|
||||
}
|
||||
|
||||
is BinaryOperation -> {
|
||||
BINARY_OPERATION -> {
|
||||
while (
|
||||
operationStack.firstOrNull()?.let {
|
||||
it is BinaryOperation &&
|
||||
it.priority <= element.priority
|
||||
it.priority <= (element as BinaryOperation).priority
|
||||
} == true
|
||||
) {
|
||||
this += operationStack.removeFirst() as CalculationToken
|
||||
}
|
||||
operationStack.addFirst(element)
|
||||
}
|
||||
|
||||
NUMBER -> {
|
||||
this += (element as Operand)
|
||||
if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation
|
||||
}
|
||||
}
|
||||
}
|
||||
while (operationStack.isNotEmpty()) {
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import java.math.BigDecimal
|
||||
|
||||
sealed class ExpressionElement {
|
||||
abstract val elementType: ElementType
|
||||
}
|
||||
|
||||
interface CalculationToken
|
||||
|
||||
class Operand(
|
||||
private val value: String
|
||||
) : ExpressionElement(), CalculationToken {
|
||||
override var elementType: ElementType = ElementType.NUMBER
|
||||
|
||||
private lateinit var bigDecimalValue: BigDecimal
|
||||
|
||||
override fun toString() = value
|
||||
fun toBigDecimal(): BigDecimal {
|
||||
if (!::bigDecimalValue.isInitialized) bigDecimalValue = value.toBigDecimal()
|
||||
return bigDecimalValue
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (other !is Operand) return false
|
||||
return value == other.value ||
|
||||
toBigDecimal() == other.toBigDecimal()
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return toBigDecimal().hashCode()
|
||||
}
|
||||
}
|
||||
|
||||
open class Expression(
|
||||
val elements: List<ExpressionElement>,
|
||||
) : ExpressionElement() {
|
||||
constructor(vararg elements: ExpressionElement) : this(elements.toList())
|
||||
|
||||
override val elementType = ElementType.EXPRESSION
|
||||
override fun toString() = elements.joinToString("")
|
||||
}
|
||||
|
||||
class BracketExpression(elements: List<ExpressionElement>) : Expression(listOf(OpenBracket) + elements + CloseBracket)
|
||||
|
||||
sealed class Bracket(private val value: String) : ExpressionElement() {
|
||||
override val elementType = ElementType.BRACKET
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
object OpenBracket : Bracket("(")
|
||||
object CloseBracket : Bracket(")")
|
||||
|
||||
sealed class OperationElement : ExpressionElement() {
|
||||
abstract val value: String
|
||||
abstract val isUnary: Boolean
|
||||
}
|
||||
|
||||
sealed class UnaryOperation(
|
||||
override val value: String,
|
||||
val isPrefix: Boolean
|
||||
) : OperationElement(), CalculationToken {
|
||||
override val elementType = ElementType.UNARY_OPERATION
|
||||
override val isUnary = true
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
object UnaryMinus : UnaryOperation("-", true)
|
||||
object UnaryPlus : UnaryOperation("+", true)
|
||||
object Sinus : UnaryOperation("sin", true)
|
||||
object Sqrt : UnaryOperation("sqrt", true)
|
||||
object Factorial : UnaryOperation("!", false)
|
||||
|
||||
sealed class BinaryOperation(
|
||||
override val value: String,
|
||||
val priority: Int,
|
||||
) : OperationElement(), CalculationToken {
|
||||
override val elementType = ElementType.BINARY_OPERATION
|
||||
override val isUnary = false
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
object BinaryMinus : BinaryOperation("-", 3)
|
||||
object BinaryPlus : BinaryOperation("+", 3)
|
||||
object Multiplication : BinaryOperation("*", 2)
|
||||
object Division : BinaryOperation("/", 2)
|
||||
object Power : BinaryOperation("^", 1)
|
||||
|
||||
enum class ElementType {
|
||||
NUMBER,
|
||||
BRACKET,
|
||||
UNARY_OPERATION,
|
||||
BINARY_OPERATION,
|
||||
EXPRESSION,
|
||||
}
|
||||
|
||||
enum class Brackets(
|
||||
val bracket: Bracket,
|
||||
) {
|
||||
OPEN_BRACKET(OpenBracket),
|
||||
CLOSE_BRACKET(CloseBracket);
|
||||
|
||||
companion object {
|
||||
val typeMap = entries.associateBy { it.bracket.toString() }
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import com.google.common.math.BigIntegerMath.factorial
|
||||
import java.math.MathContext.DECIMAL128
|
||||
import java.util.function.BiFunction
|
||||
import java.util.function.Function
|
||||
import kotlin.math.sin
|
||||
|
||||
interface UnaryOperationFunction<T: UnaryOperation> : Function<Operand, Operand>
|
||||
interface BinaryOperationFunction<T: BinaryOperation> : BiFunction<Operand, Operand, Operand>
|
||||
|
||||
object UnaryMinusFunction : UnaryOperationFunction<UnaryMinus> {
|
||||
override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toOperand()
|
||||
}
|
||||
|
||||
object UnaryPlusFunction : UnaryOperationFunction<UnaryPlus> {
|
||||
override fun apply(operand: Operand) = operand
|
||||
}
|
||||
|
||||
object SinusFunction : UnaryOperationFunction<Sinus> {
|
||||
override fun apply(operand: Operand) = sin(operand.toBigDecimal().toDouble()).toOperand()
|
||||
}
|
||||
|
||||
object FactorialFunction : UnaryOperationFunction<Factorial> {
|
||||
override fun apply(operand: Operand) =
|
||||
factorial(operand.toBigDecimal().toInt()).toOperand()
|
||||
}
|
||||
|
||||
object SqrtFunction : UnaryOperationFunction<Sqrt> {
|
||||
override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toOperand()
|
||||
}
|
||||
|
||||
object BinaryMinusFunction : BinaryOperationFunction<BinaryMinus> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() - second.toBigDecimal()).toOperand()
|
||||
}
|
||||
|
||||
object BinaryPlusFunction : BinaryOperationFunction<BinaryPlus> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() + second.toBigDecimal()).toOperand()
|
||||
}
|
||||
object MultiplicationFunction : BinaryOperationFunction<Multiplication> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() * second.toBigDecimal()).toOperand()
|
||||
}
|
||||
|
||||
object DivisionFunction : BinaryOperationFunction<Division> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() / second.toBigDecimal()).toOperand()
|
||||
}
|
||||
|
||||
object PowerFunction : BinaryOperationFunction<Power> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal().pow(second.toBigDecimal().toInt())).toOperand()
|
||||
}
|
||||
|
||||
fun Number.toOperand() = Operand(toString())
|
||||
@@ -1,128 +0,0 @@
|
||||
package ru.darktale.calc
|
||||
|
||||
import jakarta.inject.Inject
|
||||
|
||||
interface Parser {
|
||||
fun parse(expression: String): Expression
|
||||
}
|
||||
|
||||
class NestedExpressionsParser @Inject constructor(
|
||||
private val unaryOperations: Map<String, UnaryOperation>,
|
||||
private val binaryOperations: Map<String, BinaryOperation>,
|
||||
) : Parser {
|
||||
private val operations: Set<String> = unaryOperations.keys + binaryOperations.keys
|
||||
private val maxOperLength = operations.maxBy { it.length }.length
|
||||
|
||||
override fun parse(expression: String): Expression {
|
||||
val stack = ArrayDeque<MutableList<ExpressionElement>>()
|
||||
var elements = mutableListOf<ExpressionElement>()
|
||||
var position = 0
|
||||
while (position < expression.length) {
|
||||
Brackets.typeMap[expression.substring(position..position)]?.let { bracket ->
|
||||
if (bracket == Brackets.OPEN_BRACKET) {
|
||||
elements.validateOpenBracket(position)
|
||||
stack.addFirst(elements)
|
||||
elements = mutableListOf()
|
||||
} else {
|
||||
elements.validateCloseBracket(position)
|
||||
val nestedExpression = BracketExpression(elements)
|
||||
elements = stack.removeFirstOrNull() ?: throw ParseException("Unexpected close bracket", position)
|
||||
elements += nestedExpression
|
||||
}
|
||||
position++
|
||||
} ?: run {
|
||||
elements += if (expression[position] in NUMBERS) {
|
||||
elements.validateNumber(position)
|
||||
getNumberLength(expression, position).let {
|
||||
position += it
|
||||
Operand(expression.substring(position - it until position))
|
||||
}
|
||||
} else {
|
||||
val operation = getOperation(expression, position, elements.isUnaryPrefixOperation(position))
|
||||
position += operation.value.length
|
||||
operation
|
||||
}
|
||||
}
|
||||
}
|
||||
if (stack.isNotEmpty()) throw ParseException("Unexpected end of expression, unclosed bracket")
|
||||
elements.validate()
|
||||
|
||||
return when {
|
||||
elements.isEmpty() -> EMPTY_EXPRESSION
|
||||
elements.size == 1 && elements[0] is Expression -> elements[0] as Expression
|
||||
else -> Expression(elements)
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<ExpressionElement>.validateNumber(position: Int) {
|
||||
when (this.lastOrNull()) {
|
||||
is Operand -> throw ParseException("Unexpected number after number", position)
|
||||
is Expression -> throw ParseException("Unexpected number after expression", position)
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<ExpressionElement>.validateOpenBracket(position: Int) {
|
||||
when (this.lastOrNull()) {
|
||||
is OperationElement, null -> Unit
|
||||
else -> throw ParseException("Unexpected open bracket", position)
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<ExpressionElement>.validate() {
|
||||
when (val operation = this.lastOrNull()) {
|
||||
is BinaryOperation -> throw ParseException("expression ends with binary operation")
|
||||
is UnaryOperation -> if (operation.isPrefix) throw ParseException("expression ends with prefix unary operation")
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<ExpressionElement>.validateCloseBracket(position: Int) {
|
||||
when (this.lastOrNull()) {
|
||||
is Operand, is Expression, Brackets.CLOSE_BRACKET.bracket -> Unit
|
||||
else -> throw ParseException("Unexpected close bracket", position)
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<ExpressionElement>.isUnaryPrefixOperation(position: Int) =
|
||||
when (val operation = this.lastOrNull()) {
|
||||
is Operand, is Expression -> false
|
||||
is UnaryOperation -> {
|
||||
if (operation.isPrefix) throw ParseException(
|
||||
"Not a number or expression after prefix unary operation",
|
||||
position
|
||||
)
|
||||
else false
|
||||
}
|
||||
else -> true
|
||||
}
|
||||
|
||||
private fun getOperation(expression: String, position: Int, isUnaryPrefixOper: Boolean): OperationElement {
|
||||
val acceptableOperations =
|
||||
if (isUnaryPrefixOper) unaryOperations.filter { it.value.isPrefix }
|
||||
else unaryOperations.filter { !it.value.isPrefix } + binaryOperations
|
||||
|
||||
for (length in position until minOf(position + maxOperLength, expression.length)) {
|
||||
acceptableOperations[expression.substring(position..length)]?.let { return it }
|
||||
}
|
||||
throw ParseException("Unknown operation", position)
|
||||
}
|
||||
|
||||
private fun getNumberLength(expression: String, start: Int): Int {
|
||||
var end = start
|
||||
while (end < expression.length &&
|
||||
(expression.substring(start..end).toBigDecimalOrNull() != null ||
|
||||
"${expression.substring(start..end)}0".toBigDecimalOrNull() != null)
|
||||
) end++
|
||||
return end - start
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val NUMBERS = setOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')
|
||||
}
|
||||
}
|
||||
|
||||
class ParseException(message: String, position: Int? = null) :
|
||||
Throwable("""$message${position?.let { " at $it" } ?: ""}""")
|
||||
|
||||
private val EMPTY_EXPRESSION = Expression(emptyList())
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.darktale.calc.guice
|
||||
|
||||
import com.google.inject.AbstractModule
|
||||
import com.google.inject.TypeLiteral
|
||||
import com.google.inject.multibindings.MapBinder
|
||||
import com.google.inject.multibindings.Multibinder
|
||||
import ru.darktale.calc.*
|
||||
import ru.darktale.calc.model.*
|
||||
import ru.darktale.calc.operation.*
|
||||
import ru.darktale.calc.parse.NestedExpressionsParser
|
||||
import ru.darktale.calc.parse.Parser
|
||||
|
||||
class CalculationsModule : AbstractModule() {
|
||||
private val unaryOperationMap = mapOf(
|
||||
UnaryMinus to UnaryMinusCalculation,
|
||||
UnaryPlus to UnaryPlusCalculation,
|
||||
Abs to AbsCalculation,
|
||||
Sinus to SinusCalculation,
|
||||
Cosine to CosineCalculation,
|
||||
Sqrt to SqrtCalculation,
|
||||
Factorial to FactorialCalculation,
|
||||
)
|
||||
private val binaryOperationMap = mapOf(
|
||||
BinaryMinus to BinaryMinusCalculation,
|
||||
BinaryPlus to BinaryPlusCalculation,
|
||||
Multiplication to MultiplicationCalculation,
|
||||
Division to DivisionCalculation,
|
||||
Power to PowerCalculation,
|
||||
)
|
||||
|
||||
override fun configure() {
|
||||
val binder = binder()
|
||||
|
||||
MapBinder.newMapBinder(
|
||||
binder,
|
||||
TypeLiteral.get(UnaryOperation::class.java),
|
||||
object : TypeLiteral<UnaryOperationCalculation<out UnaryOperation>>() {},
|
||||
).apply {
|
||||
unaryOperationMap.entries.forEach {
|
||||
addBinding(it.key).toInstance(it.value)
|
||||
}
|
||||
}
|
||||
|
||||
MapBinder.newMapBinder(
|
||||
binder,
|
||||
TypeLiteral.get(BinaryOperation::class.java),
|
||||
object : TypeLiteral<BinaryOperationCalculation<out BinaryOperation>>() {},
|
||||
).apply {
|
||||
binaryOperationMap.entries.forEach {
|
||||
addBinding(it.key).toInstance(it.value)
|
||||
}
|
||||
}
|
||||
|
||||
Multibinder.newSetBinder(binder, OperationToken::class.java).apply {
|
||||
(unaryOperationMap.keys + binaryOperationMap.keys + OpenBracket + CloseBracket).forEach {
|
||||
addBinding().toInstance(it)
|
||||
}
|
||||
}
|
||||
|
||||
bind(ExpressionToRplConverter::class.java).to(ExpressionToRplConverterImpl::class.java)
|
||||
bind(Calculator::class.java).to(CalculatorImpl::class.java)
|
||||
bind(Parser::class.java).to(NestedExpressionsParser::class.java)
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package ru.darktale.calc.infra
|
||||
|
||||
import com.google.inject.AbstractModule
|
||||
import com.google.inject.TypeLiteral
|
||||
import com.google.inject.multibindings.MapBinder
|
||||
import ru.darktale.calc.*
|
||||
import ru.darktale.calc.service.CalculatorService
|
||||
import ru.darktale.calc.service.CalculatorServiceImpl
|
||||
import ru.darktale.calc.service.KeyEventHandler
|
||||
import ru.darktale.calc.service.KeyEventHandlerImpl
|
||||
|
||||
class BasicModule : AbstractModule() {
|
||||
override fun configure() {
|
||||
bind(CalculatorService::class.java).to(CalculatorServiceImpl::class.java)
|
||||
bind(KeyEventHandler::class.java).to(KeyEventHandlerImpl::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
class CalculationsModule : AbstractModule() {
|
||||
private val unaryOperationMap = mapOf(
|
||||
UnaryMinus to UnaryMinusFunction,
|
||||
UnaryPlus to UnaryPlusFunction,
|
||||
Sinus to SinusFunction,
|
||||
Sqrt to SqrtFunction,
|
||||
Factorial to FactorialFunction,
|
||||
)
|
||||
private val binaryOperationMap = mapOf(
|
||||
BinaryMinus to BinaryMinusFunction,
|
||||
BinaryPlus to BinaryPlusFunction,
|
||||
Multiplication to MultiplicationFunction,
|
||||
Division to DivisionFunction,
|
||||
Power to PowerFunction,
|
||||
)
|
||||
|
||||
override fun configure() {
|
||||
val binder = binder()
|
||||
|
||||
MapBinder.newMapBinder(
|
||||
binder,
|
||||
TypeLiteral.get(UnaryOperation::class.java),
|
||||
object : TypeLiteral<UnaryOperationFunction<out UnaryOperation>>() {},
|
||||
).apply {
|
||||
unaryOperationMap.entries.forEach {
|
||||
addBinding(it.key).toInstance(it.value)
|
||||
}
|
||||
}
|
||||
|
||||
MapBinder.newMapBinder(binder, String::class.java, UnaryOperation::class.java).apply {
|
||||
unaryOperationMap.keys.forEach {
|
||||
addBinding(it.value).toInstance(it)
|
||||
}
|
||||
}
|
||||
|
||||
MapBinder.newMapBinder(
|
||||
binder,
|
||||
TypeLiteral.get(BinaryOperation::class.java),
|
||||
object : TypeLiteral<BinaryOperationFunction<out BinaryOperation>>() {},
|
||||
).apply {
|
||||
binaryOperationMap.entries.forEach {
|
||||
addBinding(it.key).toInstance(it.value)
|
||||
}
|
||||
}
|
||||
|
||||
MapBinder.newMapBinder(binder, String::class.java, BinaryOperation::class.java).apply {
|
||||
binaryOperationMap.keys.forEach {
|
||||
addBinding(it.value).toInstance(it)
|
||||
}
|
||||
}
|
||||
|
||||
bind(ExpressionToRplConverter::class.java).to(ExpressionToRplConverterImpl::class.java)
|
||||
bind(Calculator::class.java).to(CalculatorImpl::class.java)
|
||||
bind(Parser::class.java).to(NestedExpressionsParser::class.java)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package ru.darktale.calc.model
|
||||
|
||||
import java.math.BigDecimal
|
||||
|
||||
sealed class ExpressionToken {
|
||||
abstract val tokenType: TokenType
|
||||
abstract val value: String
|
||||
}
|
||||
|
||||
sealed interface CalculationToken
|
||||
|
||||
class Operand(
|
||||
override val value: String
|
||||
) : ExpressionToken(), CalculationToken {
|
||||
override var tokenType: TokenType = TokenType.NUMBER
|
||||
|
||||
private lateinit var bigDecimalValue: BigDecimal
|
||||
|
||||
override fun toString() = value
|
||||
|
||||
fun toBigDecimal(): BigDecimal {
|
||||
if (!::bigDecimalValue.isInitialized) bigDecimalValue = value.toBigDecimal()
|
||||
return bigDecimalValue
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (other !is Operand) return false
|
||||
return value == other.value ||
|
||||
toBigDecimal() == other.toBigDecimal()
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return toBigDecimal().hashCode()
|
||||
}
|
||||
}
|
||||
|
||||
sealed class Expression(
|
||||
val elements: List<ExpressionToken>
|
||||
) : ExpressionToken() {
|
||||
override val value = elements.joinToString("")
|
||||
override val tokenType = TokenType.EXPRESSION
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
class SimpleExpression(elements: List<ExpressionToken>) : Expression(elements) {
|
||||
constructor(vararg elements: ExpressionToken) : this(elements.toList())
|
||||
}
|
||||
|
||||
class BracketExpression(elements: List<ExpressionToken>) :
|
||||
Expression(listOf(OpenBracket) + elements + CloseBracket)
|
||||
|
||||
object EmptyExpression : Expression(emptyList())
|
||||
|
||||
sealed class OperationToken : ExpressionToken() {
|
||||
abstract val hasLeftOperand: Boolean
|
||||
abstract val hasRightOperand: Boolean
|
||||
abstract val priority: Int
|
||||
}
|
||||
|
||||
sealed class Bracket(
|
||||
override val value: String,
|
||||
override val tokenType: TokenType,
|
||||
) : OperationToken() {
|
||||
override val hasLeftOperand = false
|
||||
override val hasRightOperand = false
|
||||
override val priority = 0
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
object OpenBracket : Bracket("(", TokenType.OPEN_BRACKET)
|
||||
object CloseBracket : Bracket(")", TokenType.CLOSE_BRACKET)
|
||||
|
||||
|
||||
sealed class UnaryOperation: OperationToken(), CalculationToken {
|
||||
override val priority = 0
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
sealed class PrefixUnaryOperation(
|
||||
override val value: String,
|
||||
) : UnaryOperation() {
|
||||
override val tokenType = TokenType.PREFIX_UNARY_OPERATION
|
||||
override val hasLeftOperand = false
|
||||
override val hasRightOperand = true
|
||||
}
|
||||
|
||||
sealed class PrefixFunction(
|
||||
override val value: String
|
||||
) : PrefixUnaryOperation(value) {
|
||||
override val tokenType = TokenType.PREFIX_FUNCTION
|
||||
}
|
||||
|
||||
sealed class PostfixUnaryOperation(
|
||||
override val value: String,
|
||||
) : UnaryOperation() {
|
||||
override val tokenType = TokenType.POSTFIX_UNARY_OPERATION
|
||||
override val hasLeftOperand = true
|
||||
override val hasRightOperand = false
|
||||
}
|
||||
|
||||
object UnaryMinus : PrefixUnaryOperation("-")
|
||||
object UnaryPlus : PrefixUnaryOperation("+")
|
||||
object Abs : PrefixFunction("abs")
|
||||
object Sinus : PrefixFunction("sin")
|
||||
object Cosine : PrefixFunction("cos")
|
||||
object Sqrt : PrefixFunction("sqrt")
|
||||
object Factorial : PostfixUnaryOperation("!")
|
||||
|
||||
sealed class BinaryOperation(
|
||||
override val value: String,
|
||||
override val priority: Int
|
||||
) : OperationToken(), CalculationToken {
|
||||
override val tokenType = TokenType.BINARY_OPERATION
|
||||
override val hasLeftOperand = true
|
||||
override val hasRightOperand = true
|
||||
override fun toString() = value
|
||||
}
|
||||
|
||||
object BinaryMinus : BinaryOperation("-", 3)
|
||||
object BinaryPlus : BinaryOperation("+", 3)
|
||||
object Multiplication : BinaryOperation("*", 2)
|
||||
object Division : BinaryOperation("/", 2)
|
||||
object Power : BinaryOperation("^", 1)
|
||||
|
||||
enum class TokenType {
|
||||
NUMBER,
|
||||
OPEN_BRACKET,
|
||||
CLOSE_BRACKET,
|
||||
PREFIX_UNARY_OPERATION,
|
||||
PREFIX_FUNCTION,
|
||||
POSTFIX_UNARY_OPERATION,
|
||||
BINARY_OPERATION,
|
||||
EXPRESSION,
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package ru.darktale.calc.operation
|
||||
|
||||
import com.google.common.math.BigIntegerMath.factorial
|
||||
import ru.darktale.calc.model.*
|
||||
import java.math.MathContext.DECIMAL128
|
||||
import java.util.function.BiFunction
|
||||
import java.util.function.Function
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
interface UnaryOperationCalculation<T: UnaryOperation> : Function<Operand, Operand>
|
||||
interface BinaryOperationCalculation<T: BinaryOperation> : BiFunction<Operand, Operand, Operand>
|
||||
|
||||
object UnaryMinusCalculation : UnaryOperationCalculation<UnaryMinus> {
|
||||
override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toOperand()
|
||||
}
|
||||
|
||||
object UnaryPlusCalculation : UnaryOperationCalculation<UnaryPlus> {
|
||||
override fun apply(operand: Operand) = operand
|
||||
}
|
||||
|
||||
object SinusCalculation : UnaryOperationCalculation<Sinus> {
|
||||
override fun apply(operand: Operand) = sin(operand.toDouble()).toOperand()
|
||||
}
|
||||
|
||||
|
||||
object AbsCalculation : UnaryOperationCalculation<Abs> {
|
||||
override fun apply(operand: Operand) =
|
||||
if (operand.value.startsWith("-")) Operand(operand.value.substring(1))
|
||||
else operand
|
||||
}
|
||||
|
||||
object CosineCalculation : UnaryOperationCalculation<Cosine> {
|
||||
override fun apply(operand: Operand) = cos(operand.toDouble()).toOperand()
|
||||
}
|
||||
|
||||
object FactorialCalculation : UnaryOperationCalculation<Factorial> {
|
||||
override fun apply(operand: Operand) =
|
||||
factorial(operand.toBigDecimal().toInt()).toOperand()
|
||||
}
|
||||
|
||||
object SqrtCalculation : UnaryOperationCalculation<Sqrt> {
|
||||
override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toOperand()
|
||||
}
|
||||
|
||||
object BinaryMinusCalculation : BinaryOperationCalculation<BinaryMinus> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() - second.toBigDecimal()).toOperand()
|
||||
}
|
||||
|
||||
object BinaryPlusCalculation : BinaryOperationCalculation<BinaryPlus> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() + second.toBigDecimal()).toOperand()
|
||||
}
|
||||
object MultiplicationCalculation : BinaryOperationCalculation<Multiplication> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal() * second.toBigDecimal()).toOperand()
|
||||
}
|
||||
|
||||
object DivisionCalculation : BinaryOperationCalculation<Division> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal().divide(second.toBigDecimal(), DECIMAL128)).toOperand()
|
||||
}
|
||||
|
||||
object PowerCalculation : BinaryOperationCalculation<Power> {
|
||||
override fun apply(first: Operand, second: Operand) =
|
||||
(first.toBigDecimal().pow(second.toBigDecimal().toInt())).toOperand()
|
||||
}
|
||||
|
||||
fun Number.toOperand() = Operand(toString())
|
||||
fun Operand.toDouble() = this.value.toDouble()
|
||||
@@ -0,0 +1,94 @@
|
||||
package ru.darktale.calc.parse
|
||||
|
||||
import jakarta.inject.Inject
|
||||
import ru.darktale.calc.model.*
|
||||
import ru.darktale.calc.model.TokenType.*
|
||||
|
||||
interface Parser {
|
||||
fun parse(expression: String): Expression
|
||||
}
|
||||
|
||||
class NestedExpressionsParser @Inject constructor(
|
||||
operationTokens: Set<OperationToken>,
|
||||
) : Parser {
|
||||
private val tokensByType = operationTokens.groupBy { it.tokenType }
|
||||
|
||||
override fun parse(expression: String): Expression {
|
||||
val stack = ArrayDeque<MutableList<ExpressionToken>>()
|
||||
var elements = mutableListOf<ExpressionToken>()
|
||||
var position = 0
|
||||
while (position < expression.length) {
|
||||
val possibleTokenTypes = elements.getPossibleTokenTypes()
|
||||
val token = expression.getNextToken(position, possibleTokenTypes)
|
||||
when (token.tokenType) {
|
||||
OPEN_BRACKET -> {
|
||||
stack.addFirst(elements)
|
||||
elements = mutableListOf()
|
||||
}
|
||||
CLOSE_BRACKET -> {
|
||||
val nestedExpression = BracketExpression(elements)
|
||||
elements = stack.removeFirstOrNull() ?: throw ParseException("Unexpected close bracket", position)
|
||||
elements += nestedExpression
|
||||
}
|
||||
else -> elements += token
|
||||
}
|
||||
position += token.value.length
|
||||
}
|
||||
if (stack.isNotEmpty()) throw ParseException("Unexpected end of expression, unclosed bracket")
|
||||
elements.validate()
|
||||
|
||||
return when {
|
||||
elements.isEmpty() -> EmptyExpression
|
||||
elements.size == 1 && elements[0] is Expression -> elements[0] as Expression
|
||||
else -> SimpleExpression(elements)
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.getNextToken(position: Int, possibleTokenTypes: Set<TokenType>): ExpressionToken {
|
||||
if (NUMBER in possibleTokenTypes && this[position] in NUMBER_FIRST_CHARS) {
|
||||
var end = position
|
||||
while (end < this.length &&
|
||||
(this.substring(position..end).toBigDecimalOrNull() != null ||
|
||||
"${this.substring(position..end)}0".toBigDecimalOrNull() != null)
|
||||
) end++
|
||||
return Operand(this.substring(position until end))
|
||||
}
|
||||
|
||||
val expectedTokens = tokensByType.filter { it.key in possibleTokenTypes }
|
||||
.flatMap { it.value }
|
||||
.associateBy { it.value }
|
||||
val maxLength = expectedTokens.keys.maxBy { it.length }.length
|
||||
for (length in position until minOf(position + maxLength, this.length)) {
|
||||
expectedTokens[this.substring(position..length)]?.let { return it }
|
||||
}
|
||||
throw ParseException("Unexpected symbol", position)
|
||||
}
|
||||
|
||||
private fun List<ExpressionToken>.validate() {
|
||||
when (this.lastOrNull()?.tokenType) {
|
||||
BINARY_OPERATION -> throw ParseException("Expression ends with binary operation")
|
||||
PREFIX_UNARY_OPERATION -> throw ParseException("Expression ends with prefix unary operation")
|
||||
OPEN_BRACKET -> throw ParseException("Expression ends with open bracket")
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun List<ExpressionToken>.getPossibleTokenTypes(): Set<TokenType> =
|
||||
when (this.lastOrNull()?.tokenType) {
|
||||
null, OPEN_BRACKET, BINARY_OPERATION -> OPERANDS
|
||||
PREFIX_UNARY_OPERATION -> PREFIXED_OPERANDS
|
||||
NUMBER, POSTFIX_UNARY_OPERATION, CLOSE_BRACKET, EXPRESSION -> AFTER_OPERANDS
|
||||
PREFIX_FUNCTION -> FUNCTION_BODY
|
||||
}
|
||||
|
||||
companion object Sets {
|
||||
private val OPERANDS = setOf(PREFIX_UNARY_OPERATION, PREFIX_FUNCTION, OPEN_BRACKET, NUMBER)
|
||||
private val PREFIXED_OPERANDS = setOf(OPEN_BRACKET, NUMBER, PREFIX_FUNCTION)
|
||||
private val AFTER_OPERANDS = setOf(POSTFIX_UNARY_OPERATION, BINARY_OPERATION, CLOSE_BRACKET)
|
||||
private val FUNCTION_BODY = setOf(OPEN_BRACKET)
|
||||
private val NUMBER_FIRST_CHARS = setOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.')
|
||||
}
|
||||
}
|
||||
|
||||
class ParseException(message: String, val position: Int? = null) :
|
||||
Throwable("""$message${position?.let { " at $it" } ?: ""}""")
|
||||
@@ -1,24 +0,0 @@
|
||||
package ru.darktale.calc.service
|
||||
|
||||
import jakarta.inject.Singleton
|
||||
import kotlin.text.StringBuilder
|
||||
|
||||
interface CalculatorService {
|
||||
fun addSymbol(symbol: Char): String
|
||||
fun removeLast(): String
|
||||
}
|
||||
|
||||
@Singleton
|
||||
class CalculatorServiceImpl: CalculatorService {
|
||||
private val builder = StringBuilder()
|
||||
|
||||
override fun addSymbol(symbol: Char): String {
|
||||
builder.append(symbol)
|
||||
return builder.toString()
|
||||
}
|
||||
|
||||
override fun removeLast(): String {
|
||||
val len = builder.length
|
||||
return if (len > 0) builder.deleteAt(len - 1).toString() else ""
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package ru.darktale.calc.service
|
||||
|
||||
import jakarta.inject.Inject
|
||||
import javafx.event.EventHandler
|
||||
import javafx.scene.input.KeyCode
|
||||
import javafx.scene.input.KeyEvent
|
||||
import ru.darktale.calc.CalcController
|
||||
|
||||
interface KeyEventHandler : EventHandler<KeyEvent>
|
||||
|
||||
class KeyEventHandlerImpl : KeyEventHandler {
|
||||
@Inject
|
||||
private lateinit var calcController: CalcController
|
||||
|
||||
override fun handle(keyEvent: KeyEvent) {
|
||||
println(keyEvent)
|
||||
if (keyEvent.code == KeyCode.BACK_SPACE) calcController.removeLast()
|
||||
else calcController.addSymbol(keyEvent.character.toCharArray()[0])
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<?import javafx.geometry.Insets?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<?import javafx.scene.control.Button?>
|
||||
|
||||
<?import javafx.scene.layout.HBox?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<VBox alignment="CENTER" spacing="20.0" xmlns:fx="http://javafx.com/fxml"
|
||||
fx:controller="ru.darktale.calc.CalcController">
|
||||
<padding>
|
||||
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>
|
||||
</padding>
|
||||
<HBox>
|
||||
<TextField minWidth="300" fx:id="calcField" editable="false"/>
|
||||
</HBox>
|
||||
<HBox>
|
||||
<Button text="1" onAction="#on1Click"/>
|
||||
<Button text="2" onAction="#on2Click"/>
|
||||
<Button text="3" onAction="#on3Click"/>
|
||||
</HBox>
|
||||
<HBox>
|
||||
<Button text="4" onAction="#on4Click"/>
|
||||
<Button text="5" onAction="#on5Click"/>
|
||||
<Button text="6" onAction="#on6Click"/>
|
||||
</HBox>
|
||||
<HBox>
|
||||
<Button text="7" onAction="#on7Click"/>
|
||||
<Button text="8" onAction="#on8Click"/>
|
||||
<Button text="9" onAction="#on9Click"/>
|
||||
</HBox>
|
||||
<HBox>
|
||||
<Button text="0" minWidth="50" onAction="#on0Click"/>
|
||||
<Button text="." onAction="#onDotClick"/>
|
||||
</HBox>
|
||||
</VBox>
|
||||
@@ -9,6 +9,9 @@ import io.mockk.verify
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.assertDoesNotThrow
|
||||
import org.junit.jupiter.api.extension.ExtendWith
|
||||
import ru.darktale.calc.model.*
|
||||
import ru.darktale.calc.operation.BinaryOperationCalculation
|
||||
import ru.darktale.calc.operation.UnaryOperationCalculation
|
||||
import java.math.BigDecimal
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
@@ -18,10 +21,10 @@ class CalculatorImplTest {
|
||||
private lateinit var converter: ExpressionToRplConverter
|
||||
|
||||
@MockK
|
||||
private lateinit var unaryFunctions: Map<UnaryOperation, UnaryOperationFunction<out UnaryOperation>>
|
||||
private lateinit var unaryFunctions: Map<UnaryOperation, UnaryOperationCalculation<out UnaryOperation>>
|
||||
|
||||
@MockK
|
||||
private lateinit var binaryFunctions: Map<BinaryOperation, BinaryOperationFunction<out BinaryOperation>>
|
||||
private lateinit var binaryFunctions: Map<BinaryOperation, BinaryOperationCalculation<out BinaryOperation>>
|
||||
|
||||
@InjectMockKs
|
||||
private lateinit var calculator: CalculatorImpl
|
||||
@@ -32,7 +35,7 @@ class CalculatorImplTest {
|
||||
every { binaryFunctions[BinaryMinus] } returns mockk {
|
||||
every { apply(any(Operand::class), any(Operand::class)) } returns Operand("1")
|
||||
}
|
||||
val expression = Expression()
|
||||
val expression = SimpleExpression()
|
||||
val result = assertDoesNotThrow { calculator.calculate(expression) }
|
||||
|
||||
verify { converter.convert(expression) }
|
||||
@@ -47,7 +50,7 @@ class CalculatorImplTest {
|
||||
every { unaryFunctions[UnaryMinus] } returns mockk {
|
||||
every { apply(any(Operand::class)) } returns Operand("-2")
|
||||
}
|
||||
val expression = Expression()
|
||||
val expression = SimpleExpression()
|
||||
val result = assertDoesNotThrow { calculator.calculate(expression) }
|
||||
|
||||
verify { converter.convert(expression) }
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.Arguments
|
||||
import org.junit.jupiter.params.provider.ArgumentsProvider
|
||||
import org.junit.jupiter.params.provider.ArgumentsSource
|
||||
import ru.darktale.calc.model.*
|
||||
import java.util.stream.Stream
|
||||
import kotlin.test.assertContentEquals
|
||||
|
||||
@@ -24,31 +25,31 @@ class ExpressionProvider : ArgumentsProvider {
|
||||
override fun provideArguments(context: ExtensionContext): Stream<out Arguments> =
|
||||
Stream.of(
|
||||
Arguments.of(
|
||||
Expression(Operand("3"), BinaryPlus, Operand("2")),
|
||||
SimpleExpression(Operand("3"), BinaryPlus, Operand("2")),
|
||||
listOf(Operand("3"), Operand("2"), BinaryPlus)
|
||||
),
|
||||
Arguments.of(
|
||||
Expression(Operand("3"), BinaryPlus, Operand("2"), BinaryPlus, Operand("1")),
|
||||
SimpleExpression(Operand("3"), BinaryPlus, Operand("2"), BinaryPlus, Operand("1")),
|
||||
listOf(Operand("3"), Operand("2"), BinaryPlus, Operand("1"), BinaryPlus)
|
||||
),
|
||||
Arguments.of(
|
||||
Expression(Operand("3"), BinaryPlus, OpenBracket, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
|
||||
SimpleExpression(Operand("3"), BinaryPlus, OpenBracket, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
|
||||
listOf(Operand("3"), Operand("2"), Operand("1"), BinaryPlus, BinaryPlus)
|
||||
),
|
||||
Arguments.of(
|
||||
Expression(Operand("3"), BinaryPlus, Operand("2"), Multiplication, Operand("1")),
|
||||
SimpleExpression(Operand("3"), BinaryPlus, Operand("2"), Multiplication, Operand("1")),
|
||||
listOf(Operand("3"), Operand("2"), Operand("1"), Multiplication, BinaryPlus)
|
||||
),
|
||||
Arguments.of(
|
||||
Expression(Operand("3"), Multiplication, OpenBracket, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
|
||||
SimpleExpression(Operand("3"), Multiplication, OpenBracket, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
|
||||
listOf(Operand("3"), Operand("2"), Operand("1"), BinaryPlus, Multiplication)
|
||||
),
|
||||
Arguments.of(
|
||||
Expression(UnaryMinus, Operand("3"), Multiplication, OpenBracket, UnaryMinus, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
|
||||
SimpleExpression(UnaryMinus, Operand("3"), Multiplication, OpenBracket, UnaryMinus, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
|
||||
listOf(Operand("3"), UnaryMinus, Operand("2"), UnaryMinus, Operand("1"), BinaryPlus, Multiplication)
|
||||
),
|
||||
Arguments.of(
|
||||
Expression(OpenBracket, Operand("5"), BinaryPlus, Operand("1"), CloseBracket, Factorial),
|
||||
SimpleExpression(OpenBracket, Operand("5"), BinaryPlus, Operand("1"), CloseBracket, Factorial),
|
||||
listOf(Operand("5"), Operand("1"), BinaryPlus, Factorial)
|
||||
),
|
||||
)
|
||||
|
||||
+11
-17
@@ -1,35 +1,28 @@
|
||||
package ru.darktale.calc
|
||||
package ru.darktale.calc.parse
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.assertDoesNotThrow
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.CsvSource
|
||||
import ru.darktale.calc.model.*
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
|
||||
class NestedExpressionsParserTest {
|
||||
private lateinit var unaryOperations: Map<String, UnaryOperation>
|
||||
private lateinit var binaryOperations: Map<String, BinaryOperation>
|
||||
private lateinit var operations: Set<OperationToken>
|
||||
|
||||
private lateinit var parser: NestedExpressionsParser
|
||||
|
||||
@BeforeEach
|
||||
fun setup() {
|
||||
// todo add mocks
|
||||
unaryOperations = mapOf(
|
||||
"sin" to Sinus,
|
||||
"-" to UnaryMinus,
|
||||
"+" to UnaryPlus,
|
||||
"!" to Factorial,
|
||||
operations = setOf(
|
||||
OpenBracket, CloseBracket,
|
||||
UnaryMinus, UnaryPlus, Factorial, Sinus, Abs,
|
||||
Multiplication, Division, BinaryPlus, BinaryMinus, Power,
|
||||
)
|
||||
binaryOperations = mapOf(
|
||||
"+" to BinaryPlus,
|
||||
"-" to BinaryMinus,
|
||||
"*" to Multiplication,
|
||||
"/" to Division,
|
||||
)
|
||||
parser = NestedExpressionsParser(unaryOperations, binaryOperations)
|
||||
|
||||
parser = NestedExpressionsParser(operations)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -40,7 +33,7 @@ class NestedExpressionsParserTest {
|
||||
"(1+2)", "(1+2)/(3+4)", "((1+2)*(3+4))", "(0)",
|
||||
"-1", "+0", "-.5",
|
||||
"-1*(-1)", "-1*-1",
|
||||
"sin45", "sin(45)", "sin(45*2)",
|
||||
"sin(45)", "sin(45*2)", "-abs(-2)", "abs(2)^2",
|
||||
"(5+1)!",
|
||||
)
|
||||
@DisplayName(("Parse correct expressions"))
|
||||
@@ -55,6 +48,7 @@ class NestedExpressionsParserTest {
|
||||
"(", ")", "(()", ")(", "()",
|
||||
"1++", "++1", "+1+",
|
||||
"!", "+!", "!5",
|
||||
"sin45", "abs2"
|
||||
)
|
||||
@DisplayName("Fail incorrect expressions")
|
||||
fun parseException(expression: String) {
|
||||
Reference in New Issue
Block a user