0
//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));
    }
})

The code and calculation are working fine. but it's taking multiply by default. Is there a way we can stop this default behavior and throw an error message to the user that please enter your desired operator?

I tried even with normal javascript code by splitting with space and tried to check if of +,-,*,/,^ operator but the user can still give multiple spaces then writes another variable

Help appreciated

  • I don't see a way to disable implicit multiplication in math.js - https://mathjs.org/docs/expressions/syntax.html – Jay Buckman Oct 15 '20 at 11:38
  • I guess you could download the source (https://github.com/josdejong/mathjs) and disable the implicit multiplication feature. – Jay Buckman Oct 15 '20 at 11:52

1 Answers1

0

There is currently no option to disable implicit multiplication, but there is a (currently open) github issue for that. And in the comments of that issue there is a workaround to find any implicit multiplications and throw an error if one is found.

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));
}
derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • this is working. thanks, champ. hope math.js can provide config just to disable implicit multiplications. Also, whats reason to take multiple as default why not other operators like add or subtract – Ranveer Singh Rajpurohit Oct 20 '20 at 12:18
  • I can only suspect, but also in math we do implicit multiplication if we for instance write something like `2 x + 3` – derpirscher Oct 20 '20 at 12:25