Double operator fails
Hello,
I am having problems when I have formula with "double" operators. E.g:
--4+5-> ParseError: syntax error, unexpected '4' (T_LNUMBER)+-4+5-> Exception: NXP\Exception\UnknownOperatorException-+4+5-> Exception: NXP\Exception\UnknownOperatorException
Thanks for the issue.
I won't be able to look at this for about 2 weeks, but I thought I might be able to help you with a few observations.
First, MathExecutor will not parse anything that is not valid in PHP. So write a PHP script that does what you want and see if it is valid PHP.
Second (but related to above), I suspect that you need to do something like 10 - -4 + 5. I think the issue is the first - (or plus) sign is not associated with a value to operate on. The second +/- is associated with the following value (or should be). This could be a case of precedence which should be easy to fix if that is the case.
Hope this helps and I will take a look in July.
I think that, all expressions talked in this issue (--4+5, +-4+5, -+4+5, 10--4+5) are not valid and MathExecutor lib should have no code support them. Minus or plus operators work great with both positive and negative variables and there is no problem.
$calculator = new MathExecutor();
$calculator->setVar("prevYearEarning",1000);
$calculator->setVar("thisYearEarning",-500);
echo $calculator->execute("$prevYearEarning - $thisYearEarning"); // outputs 1500
If anyone wants to execute an expression like "--4+5" successfully, the expression must be normalized before executation. For example:
function normalizeDoubleMinusPlusOperators(string $expression):string{
$expression = str_replace(" ", "", $expression);
return str_replace(["--","-+","+-","++"],["+","-","-","+"], $expression);
}
$calculator = new MathExecutor();
echo $calculator->execute(normalizeDoubleMinusPlusOperators("--4+5")); // outputs 9
Another option is surrounding all numbers with brackets to ensure it will execute successfully:
$calculator = new MathExecutor();
echo $calculator->execute("-(-4)+(5)"); // outputs 9
echo $calculator->execute("(10)-(-4)+(5)"); // outputs 19
The real test is to replicate what PHP does. Some of these expressions don't work in PHP, so no need to support them. Others are easily worked around, so not a huge priority at this point.