Skip to content

Commit 94fbb8d

Browse files
authored
Merge pull request #62 from lautis/parenthesize-default-value
Parenthesize fallback value when necessary
2 parents f49b7fb + 9e6489a commit 94fbb8d

3 files changed

Lines changed: 22 additions & 11 deletions

File tree

__testfixtures__/transform.input.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,4 @@ const foo24 = get(foo, "bar", 0) > 0;
2929
const foo25 = get(foo, "bar", 0) + 0;
3030
const foo26 = get(foo, "bar", 0) ?? 0;
3131
const foo27 = await get(foo, "bar", Promise.resolve());
32+
const foo28 = get(foo, "bar", bar || "bar");

__testfixtures__/transform.output.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,4 @@ const foo24 = (foo?.bar ?? 0) > 0;
2626
const foo25 = (foo?.bar ?? 0) + 0;
2727
const foo26 = (foo?.bar ?? 0) ?? 0;
2828
const foo27 = await (foo?.bar ?? Promise.resolve());
29+
const foo28 = foo?.bar ?? (bar || "bar");

transform.js

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ const addWithNullishCoalescing = (node, j) =>
109109
j.logicalExpression(
110110
"??",
111111
generateOptionalChain(node, j),
112-
node.value.arguments[2]
112+
parenthesizeRight(node.value.arguments[2])
113113
);
114114

115115
const swapArguments = (node, options) => {
@@ -118,24 +118,33 @@ const swapArguments = (node, options) => {
118118
return node;
119119
};
120120

121-
const parenthesize = (node, replacement) => {
122-
if (
123-
[
124-
"AwaitExpression",
125-
"BinaryExpression",
126-
"LogicalExpression",
127-
"MemberExpression"
128-
].includes(node.parentPath.value.type)
129-
) {
121+
const parenthesizedExpressions = [
122+
"AwaitExpression",
123+
"BinaryExpression",
124+
"LogicalExpression",
125+
"MemberExpression"
126+
];
127+
128+
const parenthesizeExpression = (node, replacement) => {
129+
if (parenthesizedExpressions.includes(node.parentPath.value.type)) {
130130
replacement.extra || (replacement.extra = {});
131131
replacement.extra.parenthesized = true;
132132
}
133133

134134
return replacement;
135135
};
136136

137+
const parenthesizeRight = node => {
138+
if (parenthesizedExpressions.includes(node.type)) {
139+
node.extra || (node.extra = {});
140+
node.extra.parenthesized = true;
141+
}
142+
143+
return node;
144+
};
145+
137146
const replaceGetWithOptionalChain = (node, j, shouldSwapArgs) =>
138-
parenthesize(
147+
parenthesizeExpression(
139148
node,
140149
node.value.arguments[2]
141150
? addWithNullishCoalescing(node, j)

0 commit comments

Comments
 (0)