-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain5.js
88 lines (78 loc) · 2.61 KB
/
main5.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
const myCanvas = document.getElementById("myCanvas");
myCanvas.height = window.innerHeight;
myCanvas.width = window.innerWidth;
const ctx = myCanvas.getContext("2d");
const expression = "(m-n)*(p+q)";
const { postfix, transforms } = infixToPostfixConverter(expression);
console.log(postfix, transforms);
const containerManager = new ContainerManager(expression, {
width: 30,
height: 30,
});
animate();
// give deep copy
function infixToPostfixConverter(expression) {
const postfix = [];
const stack = [];
const openingBraces = ["(", "{", "["];
const closingBraces = [")", "}", "]"];
const operation = ["+", "-", "*", "/", "**", "^"];
const containerManager = new ContainerManager(expression, {
width: 30,
height: 30,
});
const transforms = [];
const elements = [
{ label: "[", isFake: true },
...containerManager.ELEMENT,
{ label: "]", isFake: true },
];
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
let ob = openingBraces.find((value) => value === element.label);
let cb = closingBraces.find((value) => value === element.label);
let o = operation.find((value) => value === element.label);
const initialPosition = { ...element };
if (ob) {
if (!element.isFake) {
// move to final position
containerManager.arrayInfixContainer.remove(element);
containerManager.stackContainer.add(element);
// arrayInfixContainer --> stackContainer
transforms.push({ i: initialPosition, f: element });
}
stack.push(ob);
} else if (cb) {
while (true) {
const poped = stack.pop();
if (!openingBraces.find((value) => value === poped)) {
if (!element.isFake) {
containerManager.stackContainer.remove(element);
containerManager.arrayPostfixContainer.add(element);
transforms.push({ i: initialPosition, f: element });
}
postfix.push(poped);
} else {
break;
}
}
} else if (o) {
if (!element.isFake) {
// move to final position
containerManager.arrayInfixContainer.remove(element);
containerManager.stackContainer.add(element);
// arrayInfixContainer --> stackContainer
transforms.push({ i: initialPosition, f: element });
}
stack.push(o);
} else {
if (!element.isFake) {
containerManager.stackContainer.remove(element);
containerManager.arrayPostfixContainer.add(element);
transforms.push({ i: initialPosition, f: element });
}
postfix.push(element.label);
}
}
return { postfix, transforms };
}