c5fbaf749e3e9a47a7b40b98d075bc6636a922d9
[nit.git] / examples / calculator / src / calculator_logic.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013-2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Business logic of a calculator
18 module calculator_logic
19
20 class CalculatorContext
21 var result: nullable Numeric = null
22
23 var last_op: nullable Char = null
24
25 var current: nullable FlatBuffer = null
26 fun display_text: String
27 do
28 var result = result
29 var last_op = last_op
30 var current = current
31
32 var buf = new FlatBuffer
33
34 if result != null and (current == null or last_op != '=') then
35 if last_op == '=' then buf.append "= "
36
37 buf.append result.to_s
38 buf.add ' '
39 end
40
41 if last_op != null and last_op != '=' then
42 buf.add last_op
43 buf.add ' '
44 end
45
46 if current != null then
47 buf.append current.to_s
48 buf.add ' '
49 end
50
51 return buf.to_s
52 end
53
54 fun push_op( op : Char )
55 do
56 apply_last_op_if_any
57 if op == 'C' then
58 self.result = null
59 last_op = null
60 else
61 last_op = op # store for next push_op
62 end
63
64 # prepare next current
65 self.current = null
66 end
67
68 fun push_digit( digit : Int )
69 do
70 var current = current
71 if current == null then current = new FlatBuffer
72 current.add digit.to_s.chars.first
73 self.current = current
74
75 if last_op == '=' then
76 self.result = null
77 last_op = null
78 end
79 end
80
81 fun switch_to_decimals
82 do
83 var current = current
84 if current == null then current = new FlatBuffer.from("0")
85 if not current.chars.has('.') then current.add '.'
86 self.current = current
87 end
88
89 fun apply_last_op_if_any
90 do
91 var op = last_op
92
93 var result = result
94
95 var current = current
96 if current == null then current = new FlatBuffer
97
98 if op == null then
99 result = current.to_n
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)
108 end
109 self.result = result
110 self.current = null
111 end
112 end
113
114 redef universal Float
115 redef fun to_s do return to_precision(6)
116 end