I am writing a static analyser for Firebase. My approach to precedence and brackets has always been, if in doubt, whack a bracket round it. Unfortunately when writing code generation tools my output ends up with more brackets than logic :s
So the expression: (4 + 6) * 6 needs its brackets to operated correctly, but (((4) + (7) * 8) has a number of pointless brackets in it. There are some tricky cases like 5 / (7 * 6), which requires brackets despite * and / having equal precedence. To understand why 5 / (6 * 7) needs brackets you have to understand that when operators have equal precedence, by default, they associate to the left. Anyway the code to actually do this turned out to be super compact so I share it with you!
I used node-falafel which is an awesome package that allows in place source code rewrites during a bottom up parse. Woah! The function “simplify” takes an expression as a string, and returns a functionally equivalent expression but without the pointless brackets in it. Nice!