为什么Math.js在计算表达式时默认以乘法为运算符?
Why Math.js default takes multiply as operator when calculation an expression?
//Require module
const express = require('express');
const { evaluate, compile, parse } = require('mathjs');
// Express Initialize
const app = express();
const port = 8000;
app.listen(port, () => {
console.log('listen port 8000');
})
//create api
app.get('/hello_world', (req, res) => {
const expression = "A B A";
console.log(expression.length);
let response;
const scope = {
A: 5,
B: 4
}
try {
const parsedExp = parse(expression);
const compiled = parsedExp.compile();
const result = compiled.evaluate(scope);
response = {
"expression": parsedExp.toString(),
"variables": parsedExp.args,
"result": result
}
console.log("success");
res.send(JSON.stringify(response));
} catch (error) {
console.log(error);
res.send(JSON.stringify(error));
}
})
代码和计算工作正常。但它默认采用乘法。有没有一种方法可以阻止这种默认行为,并向用户抛出一条错误消息,请用户输入所需的运算符?
我什至尝试使用正常的 javascript 代码与 space 分开并尝试检查 +,-,*,/,^ 运算符但用户仍然可以给出多个 space 然后写入另一个变量
感谢帮助
目前没有选项可以禁用 implicit multiplication, but there is a (currently open) github issue for that. And in the comments of that issue there is a workaround 查找任何隐式乘法并在找到时抛出错误。
try {
const parsedExp = parse(expression);
parsedExp.traverse((node, path, parent) => {
if (node.type === 'OperatorNode' && node.op === '*' && node['implicit']) {
throw new Error('Invalid syntax: Implicit multiplication found');
}
});
...
} catch (error) {
console.log(error);
res.send(JSON.stringify(error));
}
//Require module
const express = require('express');
const { evaluate, compile, parse } = require('mathjs');
// Express Initialize
const app = express();
const port = 8000;
app.listen(port, () => {
console.log('listen port 8000');
})
//create api
app.get('/hello_world', (req, res) => {
const expression = "A B A";
console.log(expression.length);
let response;
const scope = {
A: 5,
B: 4
}
try {
const parsedExp = parse(expression);
const compiled = parsedExp.compile();
const result = compiled.evaluate(scope);
response = {
"expression": parsedExp.toString(),
"variables": parsedExp.args,
"result": result
}
console.log("success");
res.send(JSON.stringify(response));
} catch (error) {
console.log(error);
res.send(JSON.stringify(error));
}
})
代码和计算工作正常。但它默认采用乘法。有没有一种方法可以阻止这种默认行为,并向用户抛出一条错误消息,请用户输入所需的运算符?
我什至尝试使用正常的 javascript 代码与 space 分开并尝试检查 +,-,*,/,^ 运算符但用户仍然可以给出多个 space 然后写入另一个变量
感谢帮助
目前没有选项可以禁用 implicit multiplication, but there is a (currently open) github issue for that. And in the comments of that issue there is a workaround 查找任何隐式乘法并在找到时抛出错误。
try {
const parsedExp = parse(expression);
parsedExp.traverse((node, path, parent) => {
if (node.type === 'OperatorNode' && node.op === '*' && node['implicit']) {
throw new Error('Invalid syntax: Implicit multiplication found');
}
});
...
} catch (error) {
console.log(error);
res.send(JSON.stringify(error));
}