This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculatorBrain.swift
79 lines (65 loc) · 2.33 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
// CalculatorBrain.swift
//÷−+
import Foundation
struct CalculatorBrain {
private var accumulator: Double?
private enum Operation{
case constant(Double)
case unaryOperation((Double) -> Double)
case binaryOperation((Double,Double) -> Double)
case equals
}
private var operations: Dictionary<String,Operation> = [
"π": Operation.constant(Double.pi),
"e": Operation.constant(M_E),
"√": Operation.unaryOperation(sqrt),
"cos": Operation.unaryOperation(cos),
"±": Operation.unaryOperation({ -$0 }),
"×": Operation.binaryOperation({ $0 * $1 }),
"÷": Operation.binaryOperation({ $0 / $1 }),
"+": Operation.binaryOperation({ $0 + $1 }),
"-": Operation.binaryOperation({ $0 - $1 }),
"=": Operation.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()
}
}
}
private mutating func performPendingBinaryOperation() {
if pendingBinaryOperation != nil && accumulator != nil {
accumulator = pendingBinaryOperation!.perform(with: accumulator!)
pendingBinaryOperation = nil
}
}
private var pendingBinaryOperation: PendingBinaryOperation?
private struct PendingBinaryOperation {
let function: (Double, Double) -> Double
let firstOperand: Double
func perform(with secondOperand: Double) -> Double {
return function(firstOperand, secondOperand)
}
}
mutating func setOperand(_ operand: Double) {
accumulator = operand
}
var result: Double? {
get {
return accumulator
}
}
}