-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculatorBrain.swift
100 lines (82 loc) · 2.76 KB
/
CalculatorBrain.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// CalculatorBrain.swift
// Calculator
//
// Created by Richard Poutier on 8/29/17.
// Copyright © 2017 Richard Poutier. All rights reserved.
//
import Foundation
struct CalculatorBrain {
private var accumulator : Double?
var resultIsPending : Bool {
if pendingBinaryOperation != nil {
return true
} else {
return false
}
}
enum Operation {
case constant(Double)
case unaryOperation((Double) -> Double)
case binaryOperation((Double, Double) -> Double)
case equals
}
private var operations : Dictionary<String,Operation> =
["π" : .constant(Double.pi),
"e" : .constant(M_E),
"⅟x" : .unaryOperation({ 1/$0 }),
"%" : .unaryOperation({ $0 / 100 }),
"√" : .unaryOperation(sqrt),
"^2" : .unaryOperation({ $0 * $0}),
"C" : .constant(0.0),
"±" : .unaryOperation({ -$0 }),
"÷" : .binaryOperation({ $0 / $1 }),
"×" : .binaryOperation({ $0 * $1 }),
"−" : .binaryOperation({ $0 - $1 }),
"+" : .binaryOperation({ $0 + $1 }),
"=" : .equals]
mutating func performOperation(_ symbol: String) {
if let operation = operations[symbol] {
switch operation {
case .constant(let value):
accumulator = value
case .unaryOperation(let function):
if accumulator != nil {
accumulator = function(accumulator!)
}
case .binaryOperation(let function):
if accumulator != nil {
pendingBinaryOperation = PendingBinaryOperation(function: function, firstOperand: accumulator!)
accumulator = nil
}
case .equals:
performPendingBinaryOperation()
}
}
}
mutating func performPendingBinaryOperation() {
if accumulator != nil && pendingBinaryOperation != nil {
accumulator = pendingBinaryOperation?.performOperation(with: accumulator!)
}
}
private var pendingBinaryOperation : PendingBinaryOperation?
struct PendingBinaryOperation {
var function : (Double, Double) -> Double
var firstOperand : Double
mutating func performOperation(with secondOperand : Double) ->Double {
return function(firstOperand, secondOperand)
}
}
mutating func setOperand(_ value: Double) {
accumulator = value
}
var result : Double? {
return accumulator
}
func description() -> String {
if !resultIsPending {
return "\(accumulator)"
}
return ""
}
}