TomFrost / Jexl

Javascript Expression Language: Powerful context-based expression parser and evaluator
MIT License
573 stars 93 forks source link

How to use relative context #93

Closed alexander-schranz closed 4 years ago

alexander-schranz commented 4 years ago

I did see the Evaluator has a relativeContext parameter. We are currently using jexl over the jexl.evalSync function but I could not find a way to set what the relative context is. Or how it works.

Would be great if somebody could provide an example for providing a relativeContext and how to access then then absolute and relative properties. I think this feature would be interesting.

TomFrost commented 4 years ago

Hi Alexander!

relativeContext is used for subexpressions, for example collection filters. Consider employees[.age > 45].firstName. This is evaluated by passing the entire compiled syntax tree into a new Evaluator with the top-level context and no relativeContext. When it comes time to filter the employees collection, it instantiates a second Evaluator for each element of the array. It passes each one the syntax sub-tree for that subexpression, the same top-level context as the original Evaluator, as well as a relativeContext of the individual employee being evaluated in that iteration. That relativeContext is what's accessed when the subexpression accesses a property with a leading dot.

Hope that makes sense! This isn't exposed the public API for Jexl because it's not intended to be used by the end-user; just an internal mechanism to track what leading-dot identifiers should be accessing.

alexander-schranz commented 4 years ago

@TomFrost Thank you for your fast response. Now I understand it. So I think we will go with something like introduce a _relative or _root variable.