Skip to content

Commit

Permalink
feat: add optional chaining support
Browse files Browse the repository at this point in the history
Closes #424
  • Loading branch information
davidbonnet committed Jan 2, 2021
1 parent 325fdb3 commit 8c3ef44
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"name": "astring",
"version": "1.4.3",
"version": "1.4.4",
"description": "JavaScript code generator from an ESTree-compliant AST.",
"main": "./dist/astring.js",
"module": "./src/astring.js",
"bin": {
"astring": "./bin/astring"
"astring": "bin/astring"
},
"scripts": {
"build": "babel src/astring.js --out-file dist/astring.js --source-maps --no-comments",
Expand Down
16 changes: 15 additions & 1 deletion src/astring.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const EXPRESSIONS_PRECEDENCE = {
SequenceExpression: 20,
// Operations
MemberExpression: 19,
ChainExpression: 19,
CallExpression: 19,
NewExpression: 19,
// Other definitions
Expand Down Expand Up @@ -918,8 +919,14 @@ export const baseGenerator = {
} else {
this[node.callee.type](node.callee, state)
}
if (node.optional) {
state.write('?.')
}
formatSequence(state, node['arguments'])
},
ChainExpression(node, state) {
this[node.expression.type](node.expression, state)
},
MemberExpression(node, state) {
if (
EXPRESSIONS_PRECEDENCE[node.object.type] <
Expand All @@ -932,11 +939,18 @@ export const baseGenerator = {
this[node.object.type](node.object, state)
}
if (node.computed) {
if (node.optional) {
state.write('?.')
}
state.write('[')
this[node.property.type](node.property, state)
state.write(']')
} else {
state.write('.')
if (node.optional) {
state.write('?.')
} else {
state.write('.')
}
this[node.property.type](node.property, state)
}
},
Expand Down
1 change: 1 addition & 0 deletions src/tests/fixtures/syntax/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ let i = {
...d,
a
};
a?.['b']?.[0]?.(1);

0 comments on commit 8c3ef44

Please sign in to comment.