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.
- Most expressions are represented like function invocations in programming, e.g.
get("population"),log2(get("population")). - Symbolic math operators (
+ - * / %) and parentheses work like in high school math, e.g.((3 + 4) * 2) / 7. That is, the formula should contain3 + 4instead of+(3, 4). - Symbolic decision operators also work with operands on both sides, instead of like function invocations.
So
get("foo") != 4instead of!=(get("foo"), 4). - Strings must always be wrapped in quotation marks, e.g.
concat("egg", "s")notconcat(egg, s). &operator concatenates strings, as in spreadsheet programs.
// Input
2 + 2
// Output
["+", 2, 2]// Input
max(3, log2(6))
// Output
["max", 3, ["log2", 6]]// Input
((3 + get("num")) * 2) / 7
// Output
["/", ["*", ["+", 3, get("num")], 2], 7]// Input
"name: " & get("name")
// Output
["concat", ["name ", ["get", "name"]]]The module exports two functions so you can transform in both directions:
formulaToExpressiontransforms (string) formulas to (array) expressions.expressionToFormulatransforms expressions to formulas.
import jamsession from '@mapbox/expression-jamsession';
jamsession.formulaToExpression("3 + 4"); // ["+", 3, 4]
jamsession.expressionToFormula(["+", 3, 4]); // "3 + 4"This library should work in IE11+. It uses a Set, so you might get it working in older browsers by adding a polyfill.
- You can use this library to create expressions that are syntactically acceptable but invalid as Mapbox GL expressions, e.g.
get(true)outputs["get", true], which fails. - You cannot use JSON object literal arguments to the
literalexpression. This is allowed in the spec; but objects are not supported by jsep and the use case for this type of expression is kind of an edge case — so it's probably not worth trying to adjust the parser to support this edge case. If you disagree, please consider filing an issue and/or PR.
Pull Requests to main automatically publish a new version based on the PR's title prefix (major:, minor: or patch:) to the npmjs registry.
The published version in the registry is the source of truth for the package version, but you can manually increment the package.json's version.
For testing in downstream projects, you can manually trigger the "NPM release" workflow on a branch to publish a pre-release tagged with the short commit sha (e.g. 0.5.0-aa79c6a) under the npm prerelease dist-tag, without affecting latest. Check the workflow results for the published version.