-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
122 lines (100 loc) · 2.9 KB
/
script.js
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const split = (expression, operator) =>{
const result = []
braces = 0;
currentBlock="";
for(var i=0; i < expression.length ; i++){
var currentPos=expression[i];
if(currentPos == '('){
braces++;
}else if(currentPos == ')'){
braces--;
}
if(braces == 0 && currentPos == operator){
result.push(currentBlock);
currentBlock="";
}else{
currentBlock+=currentPos;
}
}
if (currentBlock != "") {
result.push(currentBlock);
}
return result;
}
const parsePLusExpression = (expression) =>{
//list of seperated string numbers by splitting the expression string by '+' operator
const numberString = split(expression,'+');
var result = 0;
var numbers = [];
for(var i= 0; i < numberString.length; i++)
{
numbers.push(parseMinusExpression(numberString[i]));
}
//accumulate all values
for(var i= 0; i < numbers.length; i++)
{
result+=numbers[i];
}
return result;
};
const parseMinusExpression = (expression) => {
const numberString = split(expression,'-');
var numbers = [];
for(var i = 0; i < numberString.length; i++)
{
numbers.push(parseDivisionExpression(numberString[i]));
}
var result = numbers[0];
for(var i= 1; i < numbers.length; i++)
{
result-=numbers[i];
}
return result;
};
const parseDivisionExpression = (expression) => {
const numberString = split(expression,'/');
var numbers = [];
for(var i = 0; i < numberString.length; i++)
{
numbers.push(parseMultiplicationExpression(numberString[i]));
}
var result = numbers[0];
for(var i= 1; i < numbers.length; i++)
{
result/=numbers[i];
}
return result;
};
const parseMultiplicationExpression = (expression) =>{
//list of seperated string numbers by splitting the expression string by '*' operator
const numberString = split(expression,'*');
var numbers = [];
//return every element to a number
for(var i = 0; i < numberString.length; i++){
exp = numberString[i];
if(exp[0]=='('){
exp = exp.substr(1, exp.length - 2);
numbers.push(parsePLusExpression(exp));
}
else{
numbers.push(+numberString[i]);
}
}
var result = 1;
//multiplicate all values
for(var i = 0; i < numbers.length; i++){
result*=numbers[i];
}
return result;
};
const calculate = () => {
const expressionNode = document.getElementById('expression');
const resultNode = document.getElementById('result');
const expression = expressionNode.value;
const result = parsePLusExpression(expression);
resultNode.value = String(result);
};
const reset = () => {
document.getElementById('expression').value="";
document.getElementById('result').value="";
};