@mapbox/expression-jamsession
Write Mapbox GL expressions in a more familiar, handwritable, spreadsheet-like, programming-like syntax.
This library translates these handwritten formulas into valid spec-compliant Mapbox GL expressions that you can use in a Mapbox style.
Formula syntax features
- Arithmetic operators (
+ - * /
) and parentheses work like in high school math, e.g. ((3 + 4) * 2) / 7
. - Expressions are represented like function invocations in programming, e.g.
get("population")
, log2(get("population"))
. &
operator concatenates strings, as in spreadsheet programs.
2 + 2
["+", 2, 2]
max(3, log2(6))
["max", 3, ["log2", 6]]
((3 + get("num")) * 2) / 7
["/", ["*", ["+", 3, get("num")], 2], 7]
"name: " & get("name")
["concat", ["name ", ["get", "name"]]]
Usage
The module exports two functions so you can transform in both directions:
formulaToExpression
transforms (string) formulas to (array) expressions.expressionToFormula
transforms expressions to formulas.
import jamsession from '@mapbox/expression-jamsession';
jamsession.formulaToExpression("3 + 4");
jamsession.expressionToFormula(["+", 3, 4]);
Caveats
- You can use this library to create expressions that are syntactically acceptable but invalid as Mapbox GL expressions, e.g.
notARealExpression(true)
outputs ["notARealExpression", true]
.