node.jsbabeljsbabel-parser

Babel get array element at index N


I am rebuilding a program's AST and one of the conditions I have is to obtain given array's element at index N. To see how I should build this I went to the AST Explorer as usual and saw how this statement is build:

arr[0];

The output is:

{
        "type": "MemberExpression",
        "start": 0,
        "end": 4,
        "object": {
          "type": "Identifier",
          "start": 0,
          "end": 1,
          "name": "a"
        },
        "property": {
          "type": "Literal",
          "start": 2,
          "end": 3,
          "value": 0,
          "raw": "0"
        },
        "computed": true,
        "optional": false
      }

Since in Babel for numeric literals we use numericLiteral I tried this:

memberExpression(identifier(<myArrayNameAsAString>), numericLiteral(0))

Which surprisingly threw the error:

Error: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead got "NumericLiteral"

Now I started wondering how does Babel build such an AST in the first place. So I gave this expression:

arr[0]

And got this output (from Babel):

MemberExpression: {
  {
    ...,
    type: 'Identifier',
    name: 'arr'
  },
  {
    ...,
    type: 'NumericLiteral',
    value: 0
  }
}

It looks like Babel is able to build exactly what I want to build but when I do it it throws me an error.

As an alternative I looked at other ways to achieve this, such as using .at. However, the operation is not yet widely adopted and I would like to avoid it.


Solution

  • After debugging deeper Babel requires the property computed to be true. It has an internal validator that looks like this:

    const normal = (0, _utils.assertNodeType)("Identifier", "PrivateName");
    const computed = (0, _utils.assertNodeType)("Expression");
    

    In the case that the property computed is not set the only 2 allowed options are Identifier and PrivateName.