-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculatorLogic.js
More file actions
86 lines (83 loc) · 2.18 KB
/
Copy pathcalculatorLogic.js
File metadata and controls
86 lines (83 loc) · 2.18 KB
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
function inToPostfix(equation) {
//console.log("Infix: ", equation);
const precedence = {
"+": 1,
"-": 1,
"*": 2,
"/": 2
};
let output = [];
let operationStack = [];
let currentNumber = '';
const flushNumber = () => {
if (currentNumber !== '') {
output.push(currentNumber);
currentNumber = '';
}
}
equation.forEach((value) => {
//console.log("Processing: ", value);
if( !isNaN(value) && value !== ' ') {
currentNumber += value;
} else {
flushNumber();
if (value === "(") {
operationStack.push(value);
} else if (value === ")") {
while (operationStack.length > 0 && operationStack[operationStack.length - 1] !== "(") {
output.push(operationStack.pop());
}
operationStack.pop();
} else {
if(operationStack.length > 0){
while(precedence[value] <= precedence [operationStack[operationStack.length - 1]]) {
output.push(operationStack.pop());
}
}
operationStack.push(value);
}
}
});
flushNumber();
while(operationStack.length > 0) {
output.push(operationStack.pop());
}
console.log(output);
return output;
}
function calculatePostFix(postfix) {
//console.log(postfix);
let operation, a, b;
let stack = [];
postfix.forEach((value) => {
//console.log("Processing: ", value);
if( !isNaN(value) && isFinite(value)) {
stack.push(value);
console.log("Pushing: ", value);
} else {
operation = value;
b = Number(stack.pop());
a = Number(stack.pop());
console.log("Performing: ",a, operation, b);
switch (operation) {
case "+":
stack.push(a+b);
break;
case "-":
stack.push(a-b);
break;
case "*":
stack.push(a*b);
break;
case "/":
stack.push(a/b);
break;
}
}
});
if(stack.length === 1) return stack.pop();
else {
setEquation([]);
return "Error";
}
}