Lightweight Rules Engine in Javascript [closed]
I am looking for suggestions for a lightweight rules engine implemented in Javascript.
The reason for such an implementation is to build a very lightweight but fast browser-based simulation using a small set of rules (less than 20). The simulation would take half a dozen parameters and run the rules and display results in the browser without any need to go back to the server. Think of a UI with a couple radio buttons, checkboxes, text boxes and sliders to control the parameters. The simulation would quickly re-run based on any parameter change.
Solution 1:
I've implemented a (more complicated) version of what you are describing in c#, and thinking back through the code, all of it would be doable with JavaScript. I agree with the comments posted that writing your own is a viable option. It can be as simple or complex as you want it to be.
General observations for this type of rules engine (in no particular order):
Non-linear lookups are your friend. In JavaScript, this would be easy using the
obj[key] = val
syntax. Once you determine the output of a rule for a given set of parameters, cache its results so that you can use it again without executing the rule again.Determine whether or not you need to process unique combinations of inputs. For example, let's say you allow the user to enter multiple names and ask for suggestions on XYZ. In reality, you now need to run all rules against each input value. This may be irrelevant, simple, or immensely complicated (imagine a hotel reservation system that takes multiple dates, times, locations, and criteria, and makes suggestions).
setTimeout() can be used to smooth out UI behavior, but the rules you describe should execute in a few milliseconds or less, so worry about performance last. Performance is less of a concern than you might think with a basic rules engine.
Rule definitions will be easiest to manipulate if they are objects (or even simple object trees).
Don't tie UI elements to output results; meaning, put the results of the rule execution into a flexible object list so that you can create whatever visual output you want from it.
Customized output messages are very useful to a user. Meaning, rather than triggering a generic message when a condition is met, try inserting a real value into the output message like, "Your credit score is only 550. You need a minimum of a 600 to continue."
That's it off the top of my head. Good luck.
Solution 2:
Checkout the nools rule engine implemented in pure JavaScript for node.js. It has a pretty straightforward syntax for rules definitions.