From 8c3ef44ae6d273562f6e03cb890726d2cc02f9b2 Mon Sep 17 00:00:00 2001 From: David Bonnet Date: Sat, 2 Jan 2021 11:34:50 +0100 Subject: [PATCH] feat: add optional chaining support Closes #424 --- package-lock.json | 2 +- package.json | 4 ++-- src/astring.js | 16 +++++++++++++++- src/tests/fixtures/syntax/object.js | 1 + 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 6abe5809..612fe4c7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "astring", - "version": "1.4.3", + "version": "1.4.4", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index 7438b29d..6ba03c3f 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/astring.js b/src/astring.js index f5d68374..9fa75832 100644 --- a/src/astring.js +++ b/src/astring.js @@ -68,6 +68,7 @@ const EXPRESSIONS_PRECEDENCE = { SequenceExpression: 20, // Operations MemberExpression: 19, + ChainExpression: 19, CallExpression: 19, NewExpression: 19, // Other definitions @@ -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] < @@ -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) } }, diff --git a/src/tests/fixtures/syntax/object.js b/src/tests/fixtures/syntax/object.js index 017db9b8..c1c6731a 100644 --- a/src/tests/fixtures/syntax/object.js +++ b/src/tests/fixtures/syntax/object.js @@ -27,3 +27,4 @@ let i = { ...d, a }; +a?.['b']?.[0]?.(1);