-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
246 lines (240 loc) · 9.55 KB
/
index.html
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<html>
<head><style>
[v-cloak] {
display: none
}
</style></head>
<body>
<div id="calc">
<table v-cloak>
<tr><td colspan='8'><span style="text-align: right; width: 100%">Ans =
<span v-show="!isNaN(answer)">{{ answer }}</span>
<!--<span v-show="isNaN(answer) && memory[memory.length - 1] && memory[memory.length - 1].answer">{{ answer }}</span>-->
</span></td></tr>
<tr><td colspan='8'>
<div v-for="expr in memory"><input v-model="expr.content" disabled
style="text-align: right; width: 100%" type="text">
</div></td></tr>
<tr><td colspan='8'><input
v-model.trim="query"
v-on:keyup="parse"
v-on:keyup.enter="commit"
style="text-align: right; width: 100%" type="text"></td></tr>
<tr v-for="row in 5">
<td v-for="column in 8">
<label v-if="row == 1 && column <= 4">
{{ btns[row - 1][column - 1] }}
<span v-if="column == 4">
<input type="radio" :name="btns[row - 1][column - 1]" value="degree" v-model="degMode" @change="parse">
<input type="radio" :name="btns[row - 1][column - 1]" value="radian" v-model="degMode" @change="parse">
</span>
<input type="radio" name="mode" v-else :checked="column == 1" disabled>
</label>
<button v-else style="text-align: center; width: 100%" @click="btn(row-1, column-1)">{{ btns[row - 1][column - 1] }}</button>
</td>
</tr>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const calc = new Vue({
el: '#calc',
data: {
answer: null,
query: '',
degMode: "degree",
memory: [ ],
dict: {
"(": { type: "parentheses", val: "(" },
")": { type: "parentheses", val: ")" },
"+": { type: "operator", val: "+", args: 2, ftn: (a, b) => b + a },
"-": { type: "operator", val: "-", args: 2, ftn: (a, b) => b - a },
"*": { type: "operator", val: "x", args: 2, ftn: (a, b) => b * a },
"x": { type: "operator", val: "x", args: 2, ftn: (a, b) => b * a },
"×": { type: "operator", val: "x", args: 2, ftn: (a, b) => b * a },
"/": { type: "operator", val: "/", args: 2, ftn: (a, b) => b / a },
"÷": { type: "operator", val: "÷", args: 2, ftn: (a, b) => b / a },
"^": { type: "operator", val: "^", args: 2, ftn: (a, b) => Math.pow(b, a) },
"sin": { type: "function", val: "sin", args: 1, ftn: a => Math.sin(a) },
"cos": { type: "function", val: "cos", args: 1, ftn: a => Math.cos(a) },
"tan": { type: "function", val: "tan", args: 1, ftn: a => Math.tan(a) },
"√": { type: "function", val: "sqrt", args: 1, ftn: a => Math.sqrt(a) },
"sqrt": { type: "function", val: "sqrt", args: 1, ftn: a => Math.sqrt(a) },
"nrt": { type: "operator", val: "n√", args: 2, ftn: (a, b) => Math.pow(a, 1/b) },
"n√": { type: "operator", val: "n√", args: 2, ftn: (a, b) => Math.pow(a, 1/b) },
"e": { type: "variable", val: "e", args: 0, ftn: () => Math.E },
"pi": { type: "variable", val: "π", args: 0, ftn: () => Math.PI },
"π": { type: "variable", val: "π", args: 0, ftn: () => Math.PI },
"ans": { type: "variable", val: "ans", args: 0, ftn: () => calc.answer },
},
activeBtns: {
"⏎": "commit"
},
btns: [
["main", "abc", "func", "deg|rad", "<-", "->", "clear all", "opts"],
[7, 8, 9, "÷", "a^2", "a^b", "a/b", "<<"],
[4, 5, 6, "x", "√", "n√", "(", ")"],
[1, 2, 3, "-", "sin", "cos", "tan", "pi"],
[0, ".", "ans", "+", "|a|", "ln", "%", "⏎"]
],
},
computed: {
},
methods: {
btn: function(x, y) {
let btn = this.btns[x][y], specialBtn = this.activeBtns[btn];
if (specialBtn) {
//temp fix, move everything including functions to seperate api to resolve
this[specialBtn]();
} else {
this.query += btn;
this.parse();
}
},
parse: function() {
this.query = this.singlespace(this.query);
this.answer = postFixCalc(this.query, this.dict, this.degMode === "degree");
},
evaluate: function() {
},
commit: function() {
this.memory.push({ content: this.query, answer: this.answer});
this.query = this.answer.toString();
//this.answer = null;
},
singlespace: function(s) {
return s.replace(/\s+/g, ' ');
}
},
});
var LessTE_Precedence = function(a, b) {
let precedenceTable = {
"(": -1,
"+": 1, "-": 1,
"*": 2, "x": 2, "/": 2, "÷": 2,
"^": 3, "n√": 3
};
if (!b) {
//operator stack is empty
return false;
}
else if (a === ")" && b !== "(") {
return true;
}
else if (!precedenceTable[b]) {
return true;
}
else if (precedenceTable[a] <= precedenceTable[b]) {
return true;
}
else {
return false;
}
}
var splitVariables = function(term, dict) {
let parsable = term, result = [], vars = Object.keys(dict).sort((a,b) => b.length - a.length);
//below is kind of an abomination even though it works allegedly
//target = term.indexOf(Object.keys(dict).sort((a,b) => b.length - a.length).find( e => "1".includes(e)));
if (parsable.length <= 1 || parseInt(parsable).toString() == parsable) {
return [term];
}
while (parsable.length) {
let key = vars.find(e => parsable.includes(e)), target = parsable.indexOf(key), preKey, val;
if (target > -1) {
preKey = parsable.substring(0, target);
//val = parsable.substring(target, key.length);
if (preKey.length) { result.push(preKey); }
if (key.length) { result.push(key); }
parsable = parsable.substring(target + key.length);
//break;
} else {
break;
}
}
if (parsable.length) {
result.push(parsable);
}
return (result.length) ? result : [term];
}
var postFixCalc = function(infix, dict, deg) {
//postFix and solve via Djsktra's Shunting Yard
//By default, the last delimiter has priority which is only a problem when including delimiters
//To force parenthesis to have higher priority then white space, we replace all occurrences of a space after '(' or ')'
let tokens = infix.replace(/\)\s/, ")").replace(/\(\s/, "(").split(/([\s\(\)])+/).reverse(), output = [], opStack = [];
//lets use push and pop instead of shift and unshift
while (tokens.length) {
let token = tokens.pop(), splitToken = splitVariables(token, dict);
token = splitToken.shift();
if (splitToken.length) {
tokens = tokens.concat(splitToken.reverse());
}
if (dict[token]) {
let symbol = dict[token];
if (symbol.type == "operator" || symbol.val == ")") {
//it will likely be important to distinguish between left handed and right handed operators
while (LessTE_Precedence(symbol.val, opStack[opStack.length - 1])) {
if (!opStack.length) {
console.error(`Syntax Error: ${(symbol.val == ')') ? `Mismatched parenthesis` : `${symbol.val} is missing an operand`}`);
return;
}
output.push(opStack.pop());
}
if (symbol.val == ")") {
output.push(opStack.pop());
}
}
//opStack.unshift()
opStack.push(token);
}
else if (token === " " || token === "") {
//ignore
}
else if (!isNaN(parseInt(token))) {
output.push(token);
let nextToken;
do {
if (nextToken) { tokens.pop(); }
nextToken = tokens[tokens.length - 1];
} while (nextToken === " " || nextToken === "")
if (nextToken && (!dict[nextToken] ||
(dict[nextToken].type !== "operator" && nextToken !== ")"))) {
//add implied multiplication
tokens.push("*");
}
}
else {
console.error(`Unrecognized Token: ${token}`);
return;
}
}
if (opStack.length) {
output = output.concat(opStack.reverse())
opStack = [];
}
console.log("infix convert");
//now complete calculation, ideally I will strip parenthesis, but I can also just ignore them
let helper;
output = output.reverse();
while (output.length) {
helper = [...output].reverse();
let token = output.pop(), symbol = dict[token];
if (!isNaN(parseInt(token))) {
opStack.push(token);
}
else if (symbol.type !== "parentheses") {
let args = [];
for (const a in [...Array(symbol.args).keys()]) {
if (["sin", "cos", "tan"].includes(symbol.val) && deg) {
//in degree mode, convert to radians
opStack[opStack.length - 1] *= (Math.PI/180);
}
args.push(parseFloat(opStack.pop()));
}
opStack.push(symbol.ftn(...args));
}
}
return opStack[0];
}
</script>
</body>
</html>