Lightweight Rules Engine in Javascript [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
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.

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.

Checkout the nools rule engine implemented in pure JavaScript for node.js. It has a pretty straightforward syntax for rules definitions.

Rule Reactor (https://github.com/anywhichway/rule-reactor) is a light weight, fast, expressive forward chaining business rule engine leveraging JavaScript internals, lazy cross-products, and Functions as objects rather than Rete. It can be used in the browser or on the server.

This is very simple rule engine, which use server side javascript(Mozilla's Rhino engine) (maybe it will be helpfully to you)
http://jubyrajan.blogspot.com/2010/04/implementing-simple-deterministic-rule.html

I've made an example html / javascript rule engine for a product configurator. The rule engine is based on if then statements. The if then statements will be checked with an array. This array is filled with all possible options every time an options is changed.
Check out my blog for the example.
Link to my blog "Forward chaining javascript rule engine"
I think the "obj[key] = val" is the key to a javascript rule engine. Jquery helps with javascript handling.

Please check out (JSL) https://www.npmjs.com/package/lib-jsl.
From the overview document, JSL is a JSON based logic programming library meant for embedded use in JS programs. It uses JSON as its syntax as well as I/O method, and provides callbacks into the host environment for performance optimisation.

Related

Evaluating simple non-numeric non-exponential linear algebra expressions (so each step is referenceable) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
As the title says, I'm trying to research how to solve non-numeric non-exponential linear algebra expressions for a single variable and show the evaluation at each step until it's solved.
Ex: A+B(X+Z)/C = Y, solve for B
Ideally I'm thinking I would like it to output in a similar manner to how symbolab.com does it here
I have questions on a number of things:
1) How would one initialize variable constants to begin with that have no numeric value in order to be algebraically manipulable? And what type would they have? (Chars? Or something else?)
2) Does anyone have an idea of the methods symbolab is using to solve the above example?
3) I'm a fairly inexperienced coder, so before I embark on my own path, is any of what I'm asking already possible via a C# math library like SmartMathLibrary, Math.NET, or NCalc? Can you cite any examples that use only alphabet variables?
4) Does the fact that I don't need exponential operation (nor square roots) simplify this at all -- so that I might be able to do it in a fairly simple way?
5) Might the method solution have something to do with ASTs like in this question?
And more background -- why I'm trying to learn this:
I'm working on creating an VR puzzle game in unity (for gear VR/rift/and Vive) that uses primitive math manipulatives (cubes) to teach very simple (but specific) algebra rules (isolation, substitution, and inequalities.) The manipulatives pass between two tables (literally representing the LHS and RHS of an equation)...with the intended goal of isolating one cube variable. The cubes are only manipulable using simplistic algebraic rules that the user discovers through the act of play, so nothing is spoonfed. (Whether this sounds pointless or would even be useful in the manner I've come up with is aside the point -- it's really an exercise for me to gain a better grasp at programming and because I feel VR could be an interesting means of math education -- because the program wouldn't necessarily just be for math-oriented people -- it would also be for people who struggle with the way it's normally taught, and are more visual and hands-on in their approach to learning.)
Relating to my initial question, I need to figure out how to reference the user interactions to a pre-evaluated expression (or at least, that's what I think I need to do), in order to check their progress at each step (hence my interest in how symbolab.com evaluates non-numeric variables), and allow them to step-back and forward and check their answer at each point (which corresponds to various point deductions -- unless they only check their answer when they think they're finished --at which point they'd get a bonus). It's my belief that I need to write my own behind the scenes algebra parser (hence the question), because I want the initial setup to be randomized given the constraint of the game tables (only six placements above and to the bottom of each table on either side).
Here's a static walkthrough video I created that hopefully demonstrates what the actual game is meant to play like (though, I realize it may still be confusing b/c it's entirely static and has no user interaction via a gear vr/rift/vive controller.)
Ultimately, I would like to make this an open-source project on GitHub that could be used in a classroom setting.

short html/css syntax: <div a b c></div> - any reasons why not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I would like to discuss the way how I currently like to write html in cases when standard compliant syntax and semantics are not so important, like in a phonegap app (my principle then: if it works on all devices it's OK)
I make my html as short as possible in the following way:
<i x y z="0"><b a b c></b></i>
with css:
[x]{something}
[y]{something}
[z="0"]{...}
...
So this is instead of the normal class syntax which is to devious for my liking.
the pros for me:
it's short and requires less time to type code
combined with javascript it works nice to for instance toggle attribute values and then make styling dependent on the values
I guess the html is faster to process by the machine because it's shorter but I'm not sure about css, maybe css classes are processed much faster than custom attributes? < please comment
haven't found a case where it doesn't work
I would like to know whether there are any good reasons not to do this from a performance/technical perspective. But not from a 'code must be readable' perspective.
The HTML spec doesn't say what the browser should do if it encounters an invalid attribute. At worst the only thing that'll happen is your code will fail validation.
I guess the html is faster to process by the machine because it's shorter
Code that fights the spec/parser will almost invariably be slower than code that doesn't. This is because browser developers have to write special handling for non-conforming code since HTML is intended to be backwards compatible all the way to the very beginning. Saying "it's faster" because you shaved off a few bytes on an attribute name is a unfounded statement and bound to get you a room full of laughter in a code review.
when standard compliant syntax and semantics are not so important, like in a phonegap app
And what about if phonegap gets an update breaking your code because your are not standard conform?
it's short and requires less time to type code
In the beginning it might be, but it decreases maintainability drastically. So if you need to change something after a while, coding will become really slow, because you will have problems understanding your own code.
I guess the html is faster to process by the machine because it's shorter but I'm not sure about css, maybe css classes are processed much faster than custom attributes?
There won't be a noticeable difference for parsing.
A good coding style is a style that will allow you to add another person to your team and the effort to understand your code is as low as possible.

Semi-obfuscate/uglify JavaScript

I know about JS minfiers, obfuscators and minifiers. I was wondering if there is any existing tool (or any fast-to-code solution) to partially obfuscate JavaScript. By partially I mean that it should become difficult to read, but not appear as uglified/minified. It should keep indentation, but lose comments, and partially change variable names, making them unclear without converting them to "a, b, c" like an obfuscator.
The purpose of this could be to take an explicit and reusable code and make it implicit and difficult to be reused by other people, without making it impossible to work with for yourself.
Any idea from where to start to achieve this ? Maybe editing an existing obfuscator ?
[This answer is a direct response to OP's request].
Semantic Designs JavaScript obfuscator will do what you want, but you'll need two passes.
On the first pass, run it as obfuscator; it will rename identifiers (although you can control how much or how that is done), strip whitepspace and comments. If you limit its ability to rename the identifiers, you lose some the strength of the obfuscator but that's your choice.
On the second pass, run it as a prettyprinter; it will introduce nice indentation again.
(In fact, the idea for obfsucation came from building a prettyprinter; if you can print-pretty, surely it is easy to print-ugly).
From the point of view of working with the code, you are better off working with your master copy any way you like, complete with your indentation and nice commentary as documentation. When you are ready to obfsucate, you run the obfuscator, shipping the obfuscated result. Errors reported in the obfuscated result that involve obfuscated names can be mapped back to the original names, using the map of obfuscated <--> original names produced during the obfuscation step.
This a product of my company. I'd provide a link but SO hates it when I do that, so you'll have to find it via my bio or googling.
PS: It works exactly as #georg suggests, by parsing to an AST, mangling, and prettyprinting. It doesn't use esprima.
I'm not aware of a tool that would meet your specific requirements, but it seems to be relatively easy to create, given that the vital parts already exist.
parse the source into an AST, using esprima or similar
manipulate the tree in the way you want (eg. remove comments, mangle identifiers etc)
rebuild the source from the tree using escodegen

Javascript library to manage translation forms

Is anybody aware of any javascript tool (compatible with jQuery, tinymce or any other clientside library) able to manage the following requirements?
I need to show translation forms in which every field (either input or textarea) could contain some segment variables or code sections (mostly HTML).
For example:
"Hello {{firstname}}, this is your personal page."
or
"You improved your personal score of <strong>{{n}} points</strong>."
Of course I obtain these segments from a template parser and I need to show them to a set of translators that will perform localization towards many languages. I know that in many cases I can (and should!) avoid variables and code inside translation segments, but in many other cases I really can't.
The problem is: I would like to manage coherence about variables and code directly on the browser (I trust my translators but a bit more of UI/UX help is always a good thing!).
A nice approach could be providing the set of variables and code tags, ready to be inserted by means of a single click (in order to avoid mispelled variables or incorrect code syntax) and a bit of pre-submit validation to be sure everything was inserted.
I've seen this approach in other websites, such as Facebook or Freelancer.com (who have the power and the ability to reimplement the whole thing from scratch!).
Do you know about any almost-ready tool/library for this purpose?
Thank you all in advance for any suggestion.
If you are asking for a library to translate text - here is Google Translate API: https://developers.google.com/translate/?csw=1
If you are asking for a library which can take user input, perform validation, and insert into the DOM - then Jquery has everything you need.
If you are asking for something else, let me know and I'll edit my question.

Delta encoding for JSON objects [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
Is there a standard library or tool out there for computing and applying differences to JSON documents? Basically I have a bunch of largish documents that I want to keep synchronized across a network, and I would prefer to avoid having to resend their entire state each time that I want to synchronize them (since many of these variables aren't going to change). In other words, I only want to transmit the fields which changed, not retransmit the entire object. I would think that it would be convenient to have something like the following set of methods:
//Start with two distinct objects on the server
// prev represents a copy of the state of the object on the client
// next represents a copy of the state of the object on the server
//
//1. Compute a patch
patch = computePatch(prev, next);
//2. Send patch over the network
//3. Apply the patch on the client
applyPatch(prev, patch);
//Final invariant:
// prev represents an equivalent object to JSON.parse(JSON.stringify(next))
I could certainly implement one myself, but there are quite a few edge cases that need to be considered. Here are some of the straightforward (though somewhat unsatisfactory) methods that I can think of such as:
Roll my own JSON patcher. Asymptotically, this is probably the best way to go, since it would be possible to support all the relevant features of JSON documents, along with supporting some specialized methods for doing stuff like diffing ints, doubles and strings (using relative encoding/edit distance). However, JSON has a lot of special cases and I am a bit leery of trying to do this without a lot of testing, and so I would much prefer to find something that already solves this problem for me so that I can trust it, and not have to worry about network Heisenbugs showing up due to mistakes in my JSON patching
Just compute the edit distance directly between the JSON strings using dynamic programming. Unfortunately, this doesn't work if the client and server have different JSON implementations (ie the order of their fields could be serialized differently), and it is also pretty expensive being a quadratic time operation.
Use protocol buffers. Protocol buffers have a built in diff method which does exactly what I want, and they are a nice binary-serializable network friendly format. Unfortunately, because they are also strictly typed, they lack many of the advantages of using JSON such as the ability to dynamically add and remove fields. Right now this is the approach I am currently leaning towards, but it could make future maintenance really horrible as I would need to continually update each of my objects.
Do something really nasty, like make a custom protocol for each type of object, and hope that I get it right in both places (yeah right!).
Of course what I am really hoping for is for someone here on stackoverflow to come through and save the day with a reference to a space efficient javascript object differ/patcher that has been well tested in production environments and across multiple browsers.
*Update*
I started writing my own patcher, an early version of it is available at github here:
https://github.com/mikolalysenko/patcher.js
I guess since there doesn't seem to be much out here, I will instead accept as an alternative answer a list of interesting test cases for a JSON patcher.
I've been mantaining a json diff & patch library at github (yes, shameless plug):
https://github.com/benjamine/JsonDiffPatch
it handles long strings automatically using Neil Fraser's diff_match_patch lib.
it works both on browsers and server (unit tests running on both env).
(full feature list is on project page)
The only thing you probably would need, that's not implemented is the option to inject custom diff/patch functions for specific objects, but that doesn't sound hard to add, you're welcome to fork it, and even better send a pull request.
Regards,
The JSON-patch standard has been updated.
https://datatracker.ietf.org/doc/html/draft-ietf-appsawg-json-patch-10
You can find an implementation for applying patches and generating patches at https://github.com/Starcounter-Jack/Fast-JSON-Patch
I came across this question searching for implementations of json-patch. If you are rolling your own you might want to base it on this draft.
https://datatracker.ietf.org/doc/html/draft-pbryan-json-patch-00
Use JSON Patch which is the standard way to do this.
JSON Patch is a format for describing changes to a
JSON document. It can be used to avoid sending a whole document when
only a part has changed. When used in combination with the HTTP PATCH
method it allows partial updates for HTTP APIs in a standards
compliant way.
The patch documents are themselves JSON documents.
JSON Patch is specified in RFC 6902 from the IETF.
Libraries exist for most platforms and programming languages.
At the time of writing, Javascript, Python, PHP, Ruby, Perl, C, Java, C#, Go, Haskell and Erlang are supported (full list and libraries here).
Here is a list for javascript
Fast-JSON-Patch both diffs and patches, 509,361 weekly downloads on NPM
jiff both diffs and patches, 5,075 weekly downloads on npm
jsonpatch-js only applies patches, 2,014 weekly downloads in npm
jsonpatch.js only applies patches, 1,470 weekly downloads in npm
JSON8 Patch both diffs and patches, 400 weekly downloads on npm
By far, everybody (myself included), is using the Fast-JSON-Patch library. It works in NodeJS and in the browser.

Categories

Resources