-
Notifications
You must be signed in to change notification settings - Fork 0
/
inputCorrector.js
79 lines (71 loc) · 2.41 KB
/
inputCorrector.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
class InputCorrector {
constructor(input) {
this.operators = ["(", ")", "!", "√", "^", "*", "/", "+", "-"];
this.inputArray = input.split('');
this.openParenthesisQuantity = 0;
this.closedParenthesisQuantity = 0;
}
correct() {
for (let i = 0; i < this.inputArray.length; i++) {
if (this.inputArray[this.inputArray.length] === NaN) {
break;
}
this.checkThisAndNext(i);
}
this.checkForLeftoverParentheese();
this.checkLastValue();
return this.inputArray.join('');
}
inOperators(currentChar) {
for (let o of this.operators) {
if (this.inputArray[currentChar] === o) {
return true;
}
}
return false;
}
checkThisAndNext(i) {
this.writeAdditionalMultiplication(i);
if (this.inputArray[i] === "." && this.inOperators(i+1)) {
this.inputArray.splice(i, 1);
}
}
writeAdditionalMultiplication(i) {
if ((!this.operators.includes(this.inputArray[i]) || this.inputArray[i] === "!") && (this.inputArray[i+1] === "(" || this.inputArray[i+1] === "√")) {
console.log("Conditional");
this.inputArray.splice(i+1, 0, '*');
console.log(this.inputArray);
}
if (!this.operators.includes(this.inputArray[i+1]) && (this.inputArray[i] === ")" || this.inputArray[i] === "!")) {
this.inputArray.splice(i+1, 0, '*');
}
}
checkForLeftoverParentheese() {
for (let i = 0; i < this.inputArray.length; i++) {
switch (this.inputArray[i]) {
case ("("):
++this.openParenthesisQuantity;
break;
case (")"):
++this.closedParenthesisQuantity;
break;
}
}
if (this.openParenthesisQuantity > this.closedParenthesisQuantity) {
for (let i = 0; i < (this.openParenthesisQuantity - this.closedParenthesisQuantity); i++) {
this.inputArray.splice(this.inputArray.length - 1, 0, ")");
}
} else if (this.openParenthesisQuantity < this.closedParenthesisQuantity) {
for (let i = 0; i < (this.closedParenthesisQuantity - this.openParenthesisQuantity); i++) {
this.inputArray.unshift("(");
}
}
}
checkLastValue() {
const lastValuePosition = this.inputArray.length-2
const lastValue = this.inputArray[lastValuePosition];
if (lastValue !== ")" && lastValue !== "!" && this.operators.includes(lastValue)) {
this.inputArray.splice(lastValuePosition, 1);
}
}
}