-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmathOperations.js
More file actions
76 lines (65 loc) · 2.06 KB
/
mathOperations.js
File metadata and controls
76 lines (65 loc) · 2.06 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
const math = require('mathjs');
function factorial(n) {
if (n < 0) return NaN;
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
if (!isFinite(result)) break;
}
return result;
}
function isPrime(num) {
for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
if (num % i === 0) return false;
}
return num > 1;
}
function parseExpression(expression) {
// Replace √ with sqrt, handling both √n and √(...)
expression = expression.replace(/√(\d+)/g, 'sqrt($1)').replace(/√/g, 'sqrt');
// Replace factorials with a function call
expression = expression.replace(/(\d+)!/g, 'factorial($1)');
return expression;
}
function simplifyExpression(expression) {
if (expression.length > 1000) {
return expression;
}
// Check for repetitive patterns
const repetitivePattern = /(\+0\*\d+){10,}/;
if (repetitivePattern.test(expression)) {
return '1'; // Since 0^0 = 1, and all other terms are 0
}
try {
const preparedExpression = expression
.replace(/√(\d+)/g, 'sqrt($1)')
.replace(/√/g, 'sqrt');
const simplified = math.simplify(preparedExpression);
return simplified.toString().replace(/sqrt/g, '√');
} catch (error) {
console.error('Error simplifying expression:', error);
return expression; // Return original expression if simplification fails
}
}
function evaluateExpression(parsedExpression) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => reject(new Error("Evaluation timed out")), 5000);
try {
const scope = {factorial, sqrt: Math.sqrt};
const result = math.evaluate(parsedExpression, scope);
clearTimeout(timeoutId);
resolve(result);
} catch (error) {
clearTimeout(timeoutId);
reject(error);
}
});
}
module.exports = {
factorial,
isPrime,
parseExpression,
simplifyExpression,
evaluateExpression
};