Refactored computations again, split into multiple files, lots still to do
This commit is contained in:
30
app/imports/api/creature/computation/evaluateCalculation.js
Normal file
30
app/imports/api/creature/computation/evaluateCalculation.js
Normal file
@@ -0,0 +1,30 @@
|
||||
import computedValueOfVariableName from '/imports/api/creature/computation/computedValueOfVariableName.js'
|
||||
|
||||
export default function evaluateCalculation(string, memo){
|
||||
if (!string) return string;
|
||||
// Parse the string using mathjs
|
||||
let calc;
|
||||
try {
|
||||
calc = math.parse(string);
|
||||
} catch (e) {
|
||||
return string;
|
||||
}
|
||||
// Replace all symbols with known values
|
||||
let substitutedCalc = calc.transform(node => {
|
||||
if (node.isSymbolNode) {
|
||||
let val = computedValueOfVariableName(node.name, memo);
|
||||
if (val === null) return node;
|
||||
return new math.expression.node.ConstantNode(val);
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
});
|
||||
|
||||
// Evaluate the expression to a number or return with substitutions
|
||||
try {
|
||||
return substitutedCalc.eval();
|
||||
} catch (e){
|
||||
return substitutedCalc.toString();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user