silentmatt / expr-eval

Mathematical expression evaluator in JavaScript
http://silentmatt.com/javascript-expression-evaluator/
MIT License
1.18k stars 239 forks source link

Custom operators #243

Open bscbrn opened 3 years ago

bscbrn commented 3 years ago

Hi, I find the feature that allows to implement new functions in the parser very useful. However it would be nice to be able to add new operator also. For instance the bitwise operators like '|' and '&' are missing and it seems not possible to define them.

At the moment I implemented them through functions like:

` parser.functions.bitor = function (a, b) { return (a | b) }

parser.functions.bitand = function (a, b) { return (a & b) } `

but having the possibility to add an operetor would be much better.

By adding/replacing an operator could be even possible to redefine the assignment operator to perform some "reactive assignment" like Vue.set that are useful if used with Vuejs.

Any plan to add customization on operator?

Thank you

bscbrn commented 3 years ago

Based on #244 I suceeded in replacing the assignment operator as follows:

parser.binaryOps['='] = (a, b) => storeRef.commit('writeExprVar', { name: a, val: b })

the 'writeExprVar' is a vue mutation that executes the Vue.set on the named variable. It works very well. Thank you @silentmatt

I also tryed to do:

parser.binaryOps['|'] = (a, b) => (a | b); parser.binaryOps['&'] = (a, b) => (a & b);

to implement the bitwise or and and but it does not work.

silentmatt commented 3 years ago

I apparently forgot that the = functionality was defined using a binaryOps function, so that's great! I had thought it was a special case, and obviously should have checked. Glad you found that.

Unfortunately, you can't use it to add operators though. That's something I'd like to add at some point, but it's a little more involved, because you need to modify the lexer and parser so they'll recognize the strings '|' and '&' as operators. It would certainly be doable, but will take some significant modifications to the parsing engine to support.