Skip to content

Commit

Permalink
feat(removecalls): handle arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
merceyz committed Jun 20, 2019
1 parent 18e35ba commit 524fa51
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/visitors/removeUnnecessaryCalls.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,14 @@ const transforms = [
if (args.length !== 1) return;

const [arg] = args;
if (t.isLogicalExpression(arg, { operator: '&&' }) && isStringLike(arg.right)) {
if (
t.isLogicalExpression(arg, { operator: '&&' }) &&
(isStringLike(arg.right) ||
isSafeConditionalExpression(arg.right) ||
(t.isBinaryExpression(arg.right, { operator: '+' }) &&
isStringLike(arg.right.left) &&
isSafeConditionalExpression(arg.right.right)))
) {
return t.conditionalExpression(arg.left, arg.right, t.stringLiteral(''));
} else if (t.isLogicalExpression(arg, { operator: '||' }) && isStringLike(arg.right)) {
// Assume that arg.left returns a string value
Expand Down Expand Up @@ -96,13 +103,28 @@ const transforms = [
},
];

const arrayVisitor = {
ArrayExpression(path) {
for (const t of transforms) {
const result = t(path.node.elements);

if (result !== undefined) {
path.replaceWith(result);
break;
}
}
},
};

const visitor = {
CallExpression(path) {
const c = path.node.callee;
if (!t.isIdentifier(c) || !this.options.functionNames.includes(c.name)) {
return;
}

path.traverse(arrayVisitor);

for (const t of transforms) {
const result = t(path.node.arguments);

Expand Down
2 changes: 2 additions & 0 deletions test/fixtures/remove-unnecessary-calls/array/code.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const x1 = clsx(canDrop && ['on-drag-enter', isOver && 'on-drag-hover']);
const x2 = clsx(canDrop && [!isOver && 'on-drag-enter', isOver && 'on-drag-hover']);
2 changes: 2 additions & 0 deletions test/fixtures/remove-unnecessary-calls/array/output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const x1 = canDrop ? 'on-drag-enter' + (isOver ? ' on-drag-hover' : '') : '';
const x2 = canDrop ? (isOver ? 'on-drag-hover' : 'on-drag-enter') : '';

0 comments on commit 524fa51

Please sign in to comment.