@mapbox/expression-jamsession
Advanced tools
Comparing version 0.1.0 to 0.2.0
# Changelog | ||
## 0.2.0 | ||
- **[BREAKING]** Export 2 functions: `expressionToFormula` and `formulaToExpression`, so the transformation can go both ways. | ||
## 0.1.0 | ||
- Initial release. |
@@ -64,3 +64,3 @@ 'use strict'; | ||
function createExpression(input) { | ||
function formulaToExpression(input) { | ||
var ast = void 0; | ||
@@ -77,2 +77,36 @@ try { | ||
module.exports = createExpression; | ||
function expressionToFormula(expression) { | ||
var operator = expression[0]; | ||
var args = expression.slice(1).map(function (arg) { | ||
if (typeof arg === 'string') { | ||
return '"' + arg + '"'; | ||
} | ||
if (!Array.isArray(arg)) { | ||
return arg; | ||
} | ||
var argOperator = arg[0]; | ||
var argFormula = expressionToFormula(arg); | ||
if (/^[+-]$/.test(argOperator) && /^[*/]$/.test(operator)) { | ||
return '(' + argFormula + ')'; | ||
} | ||
return argFormula; | ||
}); | ||
if (operator === '+' || operator === '*' || operator === '-' || operator === '/') { | ||
return '' + args.join(' ' + operator + ' '); | ||
} | ||
if (operator === 'concat') { | ||
return args.join(' & '); | ||
} | ||
return operator + '(' + args.join(', ') + ')'; | ||
} | ||
var index = { | ||
formulaToExpression: formulaToExpression, | ||
expressionToFormula: expressionToFormula | ||
}; | ||
module.exports = index; |
{ | ||
"name": "@mapbox/expression-jamsession", | ||
"version": "0.1.0", | ||
"version": "0.2.0", | ||
"description": "Write Mapbox GL expressions in a more familiar, handwritable, spreadsheet-like, programming-like syntax.", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
@@ -9,3 +9,3 @@ # @mapbox/expression-jamsession | ||
## Features | ||
## Formula syntax features | ||
@@ -48,14 +48,19 @@ - Arithmetic operators (`+ - * /`) and parentheses work like in high school math, e.g. `((3 + 4) * 2) / 7`. | ||
## Caveats | ||
## Usage | ||
- 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]`. | ||
The module exports two functions so you can transform in both directions: | ||
## Usage | ||
- `formulaToExpression` transforms (string) formulas to (array) expressions. | ||
- `expressionToFormula` transforms expressions to formulas. | ||
Pass in a string formula and get an expression. | ||
```js | ||
import createExpression from '@mapbox/expression-jamsession'; | ||
import jamsession from '@mapbox/expression-jamsession'; | ||
createExpression('3 + 4'); // ["+", 3, 4] | ||
jamsession.formulaToExpression("3 + 4"); // ["+", 3, 4] | ||
jamsession.expressionToFormula(["+", 3, 4]); // "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]`. |
7838
87
65