1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Business logic of a calculator
16 module calculator_logic
20 # Hold the state of the calculator and its services
21 class CalculatorContext
24 # Result of the last operation
25 var result
: nullable Numeric = null
27 # Last operation pushed with `push_op`, to be executed on the next push
28 var last_op
: nullable Char = null
30 # Value currently being entered
31 var current
: nullable FlatBuffer = null
33 # Text to display on screen
34 fun display_text
: String
40 var buf
= new FlatBuffer
42 if result
!= null and (current
== null or last_op
!= '=') then
43 if last_op
== '=' then buf
.append
"= "
45 buf
.append result
.to_s
49 if last_op
!= null and last_op
!= '=' then
54 if current
!= null then
55 buf
.append current
.to_s
62 # Push operation `op`, will usually execute the last operation
70 last_op
= op
# store for next push_op
73 # prepare next current
78 fun push_digit
(digit
: Int)
81 if current
== null then current
= new FlatBuffer
82 current
.add digit
.to_s
.chars
.first
83 self.current
= current
85 if last_op
== '=' then
91 # Switch entry mode from integer to decimal
92 fun switch_to_decimals
95 if current
== null then current
= new FlatBuffer.from
("0")
96 if not current
.chars
.has
('.') then current
.add
'.'
97 self.current
= current
100 # Execute the last operation it not null
101 protected fun apply_last_op_if_any
105 var current
= current
108 if current
== null then return
111 result
= current
.to_n
112 else if result
!= null then
114 result
= result
.add
(current
.to_n
)
115 else if op
== '-' then
116 result
= result
.sub
(current
.to_n
)
117 else if op
== '/' then
118 result
= result
.div
(current
.to_n
)
119 else if op
== '*' then
120 result
= result
.mul
(current
.to_n
)
128 redef universal Float
129 redef fun to_s
do return to_precision
(6)