javascriptnode.jsmathmathjs

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

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


Solution

  • 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));
    }