1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013-2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Business logic of a calculator
18 module calculator_logic
20 class CalculatorContext
21 var result
: nullable Numeric = null
23 var last_op
: nullable Char = null
25 var current
: nullable FlatBuffer = null
26 fun display_text
: String
32 var buf
= new FlatBuffer
34 if result
!= null and (current
== null or last_op
!= '=') then
35 if last_op
== '=' then buf
.append
"= "
37 buf
.append result
.to_s
41 if last_op
!= null and last_op
!= '=' then
46 if current
!= null then
47 buf
.append current
.to_s
54 fun push_op
( op
: Char )
61 last_op
= op
# store for next push_op
64 # prepare next current
68 fun push_digit
( digit
: Int )
71 if current
== null then current
= new FlatBuffer
72 current
.add digit
.to_s
.chars
.first
73 self.current
= current
75 if last_op
== '=' then
81 fun switch_to_decimals
84 if current
== null then current
= new FlatBuffer.from
("0")
85 if not current
.chars
.has
('.') then current
.add
'.'
86 self.current
= current
89 fun apply_last_op_if_any
96 if current
== null then current
= new FlatBuffer
100 else if op
== '+' then
101 result
= result
.add
(current
.to_n
)
102 else if op
== '-' then
103 result
= result
.sub
(current
.to_n
)
104 else if op
== '/' then
105 result
= result
.div
(current
.to_n
)
106 else if op
== '*' then
107 result
= result
.mul
(current
.to_n
)
114 redef universal Float
115 redef fun to_s
do return to_precision
(6)