-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.js
More file actions
115 lines (81 loc) · 3.23 KB
/
function.js
File metadata and controls
115 lines (81 loc) · 3.23 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
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
// First of all , you can use eval function to convert strings like testStr and secondText to get result.
var testStr = "12+23/4-3/2*6";
var secondText = "5/5*2+333/2/2/2"
var firstPriorityOperators = ["/" , "*"]
var secondPriorityOperators = ["+" , "-"]
function createArray(str){
let num = ""
var resultArrayOrigin = [];
for(i=0; i < str.length; i++){
if(!/[-+*/]/.test(str[i]) || i == 0){
num = num + str[i]
}
if(/[-+*/]/.test(str[i]) && i > 0){
resultArrayOrigin.push(parseInt(num))
resultArrayOrigin.push(str[i])
num = ""
}
}
resultArrayOrigin.push(parseInt(num))
return resultArrayOrigin
}
function checkArrayHasPriority(resultArr){
if(secondPriorityOperators.some(elem=> resultArr.includes(elem))
&& (firstPriorityOperators.some(elem=> resultArr.includes(elem)))){
return completeArray(formatArray(resultArr))
}
else{
return completeArray(resultArr)
}
}
function formatArray(resultArray){
var paramFormatResult;
for (var i=0 ; i < resultArray.length; i++){
if(resultArray[i] === "*"){
paramFormatResult = resultArray[i-1] * resultArray[i+1]
resultArray.splice(i-1,3)
resultArray.splice(i-1 , 0 , paramFormatResult)
formatArray(resultArray)
}
else if(resultArray[i] === "/"){
paramFormatResult = resultArray[i-1] / resultArray[i+1]
resultArray.splice(i-1,3)
resultArray.splice(i-1 , 0 , paramFormatResult)
formatArray(resultArray)
}
}
return resultArray;
}
function completeArray(resultArray){
var paramResult;
for (var i=0 ; i < resultArray.length; i++){
if(resultArray[i] === "*"){
paramResult = resultArray[i-1] * resultArray[i+1]
resultArray.splice(i-1,3)
resultArray.splice(i-1 , 0 , paramResult)
completeArray(resultArray)
}
else if(resultArray[i] === "/"){
paramResult = resultArray[i-1] / resultArray[i+1]
resultArray.splice(i-1,3)
resultArray.splice(i-1 , 0 , paramResult)
completeArray(resultArray)
}
else if(resultArray[i] === "+"){
paramResult = resultArray[i-1] + resultArray[i+1]
resultArray.splice(i-1,3)
resultArray.splice(i-1 , 0 , paramResult)
completeArray(resultArray)
}
else if(resultArray[i] === "-"){
paramResult = resultArray[i-1] - resultArray[i+1]
resultArray.splice(i-1,3)
resultArray.splice(i-1 , 0 , paramResult)
completeArray(resultArray)
}
}
return resultArray
}
console.log(completeArray(formatArray([2,"+", 3,"*",5 ,"*",5,"-",234])))
console.log(completeArray(formatArray([2,"+", 3,"*",5 ,"+",5,"*",234])))
console.log(formatArray([1,"*",2,"*",2]))