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
18 # Hold the state of the calculator and its services
19 class CalculatorContext
20 # Result of the last operation
21 var result
: nullable Numeric = null
23 # Last operation pushed with `push_op`, to be executed on the next push
24 var last_op
: nullable Char = null
26 # Value currently being entered
27 var current
: nullable FlatBuffer = null
29 # Text to display on screen
30 fun display_text
: String
36 var buf
= new FlatBuffer
38 if result
!= null and (current
== null or last_op
!= '=') then
39 if last_op
== '=' then buf
.append
"= "
41 buf
.append result
.to_s
45 if last_op
!= null and last_op
!= '=' then
50 if current
!= null then
51 buf
.append current
.to_s
58 # Push operation `op`, will usually execute the last operation
66 last_op
= op
# store for next push_op
69 # prepare next current
74 fun push_digit
(digit
: Int)
77 if current
== null then current
= new FlatBuffer
78 current
.add digit
.to_s
.chars
.first
79 self.current
= current
81 if last_op
== '=' then
87 # Switch entry mode from integer to decimal
88 fun switch_to_decimals
91 if current
== null then current
= new FlatBuffer.from
("0")
92 if not current
.chars
.has
('.') then current
.add
'.'
93 self.current
= current
96 # Execute the last operation it not null
97 protected fun apply_last_op_if_any
103 var current
= current
104 if current
== null then current
= new FlatBuffer
107 result
= current
.to_n
108 else if op
== '+' then
109 result
= result
.add
(current
.to_n
)
110 else if op
== '-' then
111 result
= result
.sub
(current
.to_n
)
112 else if op
== '/' then
113 result
= result
.div
(current
.to_n
)
114 else if op
== '*' then
115 result
= result
.mul
(current
.to_n
)
123 redef universal Float
124 redef fun to_s
do return to_precision
(6)