EricSmekens / jsep

JavaScript Expression Parser
http://ericsmekens.github.io/jsep/
MIT License
827 stars 133 forks source link

Support continuous expressions #221

Open vishwajeet-pandey-exa opened 2 years ago

vishwajeet-pandey-exa commented 2 years ago

Right now when an expression like 2 + 3 + 4 + 5 is passed to the parse function, it's broken down into 'Binary expressions' & the tree generated is binary one & looks like what it'd be for (2 + 3) + (4 + 5):

{
  "type": "BinaryExpression",
  "operator": "+",
  "left": {
    "type": "BinaryExpression",
    "operator": "+",
    "left": {
      "type": "BinaryExpression",
      "operator": "+",
      "left": {
        "type": "Literal",
        "value": 2,
        "raw": "2"
      },
      "right": {
        "type": "Literal",
        "value": 3,
        "raw": "3"
      }
    },
    "right": {
      "type": "Literal",
      "value": 4,
      "raw": "4"
    }
  },
  "right": {
    "type": "Literal",
    "value": 5,
    "raw": "5"
  }
}

I know these are equivalent, but just to avoid extra parentheses when we try to rebuild the expression from the tree or when we try to show these in a tree form a bit better, could we generate the same thing as a 'list like' expression type where we could just show a n-ary tree instead of binary ('left' and 'right') one:

{
  "type": "ContinuousExpression",
  "operator": "+",
  "list": [
      {
        "type": "Literal",
        "value": 2,
        "raw": "2"
      },
      {
        "type": "Literal",
        "value": 3,
        "raw": "3"
      },
      {
        "type": "Literal",
        "value": 4,
        "raw": "4"
      },
      {
        "type": "Literal",
        "value": 5,
        "raw": "5"
      }
  ]
}

If nothing, could we write plugin which'd do the same thing?

LeaVerou commented 2 years ago

We can't do this by default, because our output needs to be compatible with other parsers, but it could easily be an optional plugin. It doesn't even need to modify the parser, it can just be an AST transformation (that's how we do it in Mavo that uses JSEP and also needs this).