I am developing a distributed calculator using JavaScript and PHP. The calculator should recognize parenthesis and should change the order of calculations according to parenthesis. All basic mathematical operations (*
, /
, +
, -
) have the same priority (unlike the common priority). I use the following regex to get user input and put in an array. This regex works well for positive numbers:
/\d*\.\d+|\d+|[()/*+-]/g
However, when it comes to negative numbers, it crashes because I use a recursive replacement function that replaces each pair of parenthesis (and the contents) with the result of the operations inside those parenthesis. I do this because this is a distributed calculator and I should perform each atomic operation at server side and then return the result back and show it in the history of the operations.
All I want is to detect negative numbers (to save them as only one element in the array). I think it should work in this way: when there are two consecutive operators (with zero or more whitespace characters between them), and the second operator is a minus sign (-
), the minus sign should be concatenated to the following number (as the sign of the number). In addition, if the first number is preceded by a minus sign, the sign should be concatenated to that number.