-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsemath.js
369 lines (311 loc) · 11.1 KB
/
parsemath.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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class Stack {
constructor() {
this.top = -1;
this.bottom = 0;
this.arr = [];
}
isEmpty() {
return this.top === -1;
}
push(item) {
this.arr.push(item);
this.top++;
}
pop(idx = null) {
if (!this.isEmpty()) {
this.top--;
if (idx === null) return this.arr.pop()
else {
const returnValue = this.arr[idx];
this.arr.splice(idx, 1);
return returnValue;
};
} else {
return null;
}
}
peek(idx = null) {
if (!this.isEmpty()) {
if (idx === null) return this.arr[this.top]
else return this.arr[idx];
} else {
return null;
}
}
replace(idx, newVal) {
this.arr[idx] = newVal;
}
}
// lower number means higher precendence
const precedences = {
"^": 0,
"*": 1,
"/": 1,
"+": 2,
"-": 2
};
const brackets = {
"(": 1,
")": -1,
"[": 1,
"]": -1
}
const isOperator = string => string in precedences;
const isInteger = string => /^\d+$/.test(string);
const isLetter = string => /[a-zA-Zα-ωΑ-Ω]/.test(string);
const isBracket = string => string in brackets ? [true, brackets[string]] : [false, 0];
const MAXIMUM_PRECEDENCE = 3;
const CONSTANTS = {
"e": Math.E,
"π": Math.PI,
}
let VARIABLES = CONSTANTS;
const OPERATORS = {
"^": (number1, number2) => number1**number2,
"*": (number1, number2) => number1*number2,
"/": (number1, number2) => {
if (number2 === 0) throw new Error('Division by zero error');
return number1/number2
},
"+": (number1, number2) => number1+number2,
"-": (number1, number2) => number1-number2,
"sqrt": (number1, _) => Math.sqrt(number1),
"sin": (number1, _, angleMode) => angleMode === 'rad' ? Math.sin(number1) : Math.sin(number1 * Math.PI / 180),
"cos": (number1, _, angleMode) => angleMode === 'rad' ? Math.cos(number1) : Math.cos(number1 * Math.PI / 180),
"tan": (number1, _, angleMode) => angleMode === 'rad' ? Math.tan(number1) : Math.tan(number1 * Math.PI / 180),
"asin": (number1, _, angleMode) => {
if (number1 < -1 || number1 > 1) throw new Error('Trigonometric error: asin value not in domain');
return angleMode === 'rad' ? Math.asin(number1) : Math.asin(number1) * 180 / Math.PI
},
"acos": (number1, _, angleMode) => {
if (number1 < -1 || number1 > 1) throw new Error('Trigonometric error: acos value not in domain');
return angleMode === 'rad' ? Math.acos(number1) : Math.acos(number1) * 180 / Math.PI
},
"atan": (number1, _, angleMode) => {
return angleMode === 'rad' ? Math.atan(number1) : Math.atan(number1) * 180 / Math.PI
},
"arcsin": (number1, _, angleMode) => OPERATORS["asin"](number1, _, angleMode),
"arccos": (number1, _, angleMode) => OPERATORS["acos"](number1, _, angleMode),
"arctan": (number1, _, angleMode) => OPERATORS["atan"](number1, _, angleMode),
"abs": (number1, _) => Math.abs(number1),
"ln": (number1, _) => {
if (number1 <= 0) throw new Error('Logarithm error: value not in domain')
return Math.log(number1)
}
}
const performCalculation = (number1, operator, number2 = 0, angleMode) => {
if (isNaN(number1) || isNaN(number2)) {
throw new Error('Syntax error: performing an operation on a NaN type')
}
operator = operator.toLowerCase();
if (operator in OPERATORS) {
return OPERATORS[operator](number1, number2, angleMode);
}
else return null;
}
// returns `false` if last letter is not letter, otherwise it returns all final of letters of string
const containsFinalString = firstPart => {
const finalCharacter = firstPart.charAt(firstPart.length - 1);
if (!isLetter(finalCharacter)) {
return false;
} else {
if (firstPart.length === 1) {
return finalCharacter;
} else {
let returnString = finalCharacter;
let characterIsLetter = true;
let currentSearchIndex = firstPart.length - 2
while (characterIsLetter) {
if (isLetter(firstPart.charAt(currentSearchIndex))) {
returnString = firstPart.charAt(currentSearchIndex) + returnString;
if (firstPart.length - 1 === currentSearchIndex) {
// reached start of string, return
return returnString;
} else {
currentSearchIndex--;
}
} else {
characterIsLetter = false;
}
}
return returnString;
}
}
}
const letterIsPartOfFunction = (string, idx) => {
const originalIdx = idx;
let prevIsLetter = true;
let bracketFound = false;
let functionString = string.charAt(idx);
while (prevIsLetter && idx < string.length - 1) {
idx += 1;
if (!isLetter(string.charAt(idx))) {
prevIsLetter = false;
if (isBracket(string.charAt(idx))[0]) {
bracketFound = true;
} else return false
} else {
functionString += string.charAt(idx);
}
}
let nextIsLetter = true;
bracketFound = false;
idx = originalIdx;
while (nextIsLetter && idx > 0) {
idx -= 1;
if (!isLetter(string.charAt(idx))) {
nextIsLetter = false;
} else {
functionString = string.charAt(idx) + functionString;
}
}
if (!(functionString.toLowerCase() in OPERATORS)) {
// not an operator
return false
} else {
return true
}
}
const removeInnerBrackets = (equation, enableConstants, variables, angleMode) => {
const equationValues = equation.split('');
let previousBracketValue = 0;
let maxDepth = -1;
let firstBracketIdx = -1;
let lastBracketIdx = -1;
equationValues.forEach((equationValue, idx) => {
const bracketValue = isBracket(equationValue);
if (bracketValue[0]) {
const currentValue = previousBracketValue + bracketValue[1];
if (currentValue > maxDepth && lastBracketIdx === -1) {
maxDepth = currentValue;
firstBracketIdx = idx;
} else if (previousBracketValue === maxDepth && currentValue < maxDepth && lastBracketIdx === -1) {
lastBracketIdx = idx;
}
previousBracketValue = currentValue;
}
});
if (lastBracketIdx === -1) {
throw new Error('Bracket error: imbalanced brackets');
}
const extractedEquation = equation.substring(firstBracketIdx + 1, lastBracketIdx);
if (extractedEquation === '') {
throw new Error('Bracket error: no expression within brackets');
}
let extractedEquationResult = ParseMath(extractedEquation, enableConstants, variables, angleMode);
let firstPart = equation.substring(0, firstBracketIdx);
let lastPart = equation.substring(lastBracketIdx + 1, equation.length);
if (isInteger(firstPart.charAt(firstPart.length - 1)) || (brackets[firstPart.charAt(firstPart.length - 1)] !== 1 && firstPart.charAt(firstPart.length - 1) && !letterIsPartOfFunction(firstPart, firstPart.length - 1) && !isOperator(firstPart.charAt(firstPart.length - 1)))) {
// character before bracket is number, so implied multiplication
firstPart += '*';
} else if (containsFinalString(firstPart)) {
// operation to be done to contents of brackets
let operation = containsFinalString(firstPart);
firstPart = firstPart.substring(0, firstPart.length - operation.length);
extractedEquationResult = performCalculation(extractedEquationResult, operation, null, angleMode);
if (isInteger(firstPart.charAt(firstPart.length - 1)) || (brackets[firstPart.charAt(firstPart.length - 1)] !== 1 && firstPart.charAt(firstPart.length - 1) && !letterIsPartOfFunction(firstPart, firstPart.length - 1) && !isOperator(firstPart.charAt(firstPart.length - 1)))) {
firstPart += '*'
}
};
if (isInteger(lastPart.charAt(0)) || lastPart.charAt(0) === '(' || lastPart.charAt(0) === '[' || isLetter(lastPart.charAt(0))) {
// character after bracket is number, letter or bracket, so implied multiplication
lastPart = '*' + lastPart;
}
const fullResult = firstPart + extractedEquationResult + lastPart;
return fullResult;
}
const containsBracket = equation => /[\(\)\[\]]/g.test(equation);
// for example, equation is 5 * 6 / 7 + 8
function ParseMath(equation, enableConstants = true, variables = null, angleMode = 'rad') {
equation = equation.replace(/\s/g, '');
// update variables
if (!enableConstants) VARIABLES = {}
else if (enableConstants) {
VARIABLES = CONSTANTS;
}
if (variables !== null && typeof variables === 'object') {
Object.keys(variables).forEach(variableKey => {
let variableContent = variables[variableKey];
if (typeof variableContent === 'string' && variableContent in VARIABLES) {
variableContent = VARIABLES[variableContent];
}
VARIABLES[variableKey] = variableContent;
});
}
while (containsBracket(equation)) {
equation = removeInnerBrackets(equation, enableConstants, variables, angleMode);
}
const equationValues = equation.split('');
const numbers = new Stack();
const operators = new Stack();
const pendingNumbers = new Stack();
let prevItem = 'operator';
equationValues.forEach((equationValue, idx) => {
if (equationValue != ' ') {
if (isOperator(equationValue)) {
if (prevItem === 'operator' && equationValue === '-') {
// last item was operator and this is minus, so treat as start of negative number
pendingNumbers.push(equationValue);
prevItem = 'number';
} else {
// part of equation is an operator
operators.push(equationValue);
prevItem = 'operator';
}
} else if (isInteger(equationValue)) {
// part of equation is an integer
if (idx !== equation.length - 1 && (isInteger(equation.charAt(idx + 1)) || equation.charAt(idx + 1) === '.')) {
// not end of equation string and next character is number or decimal point, so treat as one
pendingNumbers.push(equationValue);
} else if (idx !== 0 && (isInteger(equation.charAt(idx - 1)) || equation.charAt(idx - 1) === '.' || (equation.charAt(idx - 1) === '-' && prevItem === 'number'))) {
// not start of equation string, next character is not number but previous number is number, decimal point or negative
pendingNumbers.push(equationValue);
let resultingNumberString = '';
while (!pendingNumbers.isEmpty()) {
resultingNumberString += pendingNumbers.pop(0);
}
numbers.push(resultingNumberString);
} else {
numbers.push(equationValue);
}
prevItem = 'number';
} else if (equationValue === '.') {
pendingNumbers.push('.');
} else if (equationValue in VARIABLES && !letterIsPartOfFunction(equation, idx)) {
// is a variable
if (idx !== 0 && prevItem === 'number') {
// e.g. 3e, values should be multiplied together
operators.push('*');
}
equationValue = VARIABLES[equationValue].toString();
numbers.push(equationValue);
prevItem = 'number';
} else {
throw new Error('Syntax error: Variable \'' + equationValue + '\' not defined');
}
}
});
while (numbers.top !== 0) {
let highestOperator = '+';
let highestOperatorValue = MAXIMUM_PRECEDENCE;
let highestOperatorIndex = -1;
let operatorIndexes = [-1, -1];
for (let idx = 0; idx <= operators.top; idx++) {
const respectiveOperator = operators.peek(idx);
const respectiveOperatorValue = precedences[respectiveOperator];
if (respectiveOperatorValue < highestOperatorValue) {
highestOperator = respectiveOperator;
highestOperatorValue = respectiveOperatorValue;
highestOperatorIndex = idx;
operatorIndexes = [idx, idx + 1];
}
}
const resultingNumber = performCalculation(parseFloat(numbers.peek(operatorIndexes[0])), highestOperator, parseFloat(numbers.peek(operatorIndexes[1])));
numbers.pop(operatorIndexes[1]);
numbers.replace(operatorIndexes[0], resultingNumber.toString());
operators.pop(highestOperatorIndex);
}
const result = Number(numbers.pop());
return result;
}
module.exports = ParseMath;