ABSmartly.JSONExpr.Evaluator (ABSmartly v1.0.0)

Copy Markdown View Source

JSON expression evaluator for audience targeting.

Mirrors the JavaScript SDK's jsonexpr (src/jsonexpr): the same operators, the same type conversions and the same null results. Supported operators: and, or, not, null, var, value, eq, gt, gte, lt, lte, in, match, semver_eq, semver_gt, semver_gte, semver_lt, semver_lte, plus contains (an alias of in, haystack first).

  • A list expression is an implicit and; a map expression is dispatched on its operator key; anything else evaluates to nil.
  • Binary operators return nil when either operand is nil.
  • in/contains take [haystack, needle]: a list haystack matches an element that compares equal, a string haystack matches a substring (the needle is converted to a string) and a map haystack matches a key. Any other haystack gives nil.
  • match gives nil for an invalid (or over-long) regular expression.
  • semver_* convert both operands to strings and compare them as versions (see ABSmartly.Semver); they give nil when either has an empty version core.

Summary

Functions

Compare two values the way the JavaScript SDK's Evaluator.compare does.

Evaluate a JSON expression with given variables.

Functions

compare(lhs, rhs)

Compare two values the way the JavaScript SDK's Evaluator.compare does.

The right operand is converted to the left operand's type. Returns 0 when equal, 1 / -1 for an ordering, and nil when the values cannot be compared. Lists and maps only compare as equal (0) or not comparable (nil).

evaluate(expr, vars)

Evaluate a JSON expression with given variables.

Examples

iex> evaluate(%{"value" => true}, %{})
true

iex> evaluate(%{"var" => "age"}, %{"age" => 25})
25

iex> evaluate(%{"eq" => [%{"var" => "age"}, %{"value" => 25}]}, %{"age" => 25})
true