Skip to content

Commit

Permalink
feature: @putout/plugin-minify: convert-if-to-logical: ConditionalExp…
Browse files Browse the repository at this point in the history
…ression inside IfStatement (coderaiser/minify#118)
  • Loading branch information
coderaiser committed Jan 25, 2024
1 parent fad5fe7 commit c4438f7
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a && (b ? log('a and b are truthy') : log('a is truthy, b is falsy'));
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
if (a)
b ? log('a and b are truthy') : log('a is truthy, b is falsy');
4 changes: 4 additions & 0 deletions packages/plugin-minify/lib/convert-if-to-logical/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const {
isYieldExpression,
ConditionalExpression,
UnaryExpression,
isConditionalExpression,
} = types;

const parseExpressions = ({body}) => body.map(getExpression).filter(Boolean);
Expand Down Expand Up @@ -55,6 +56,9 @@ export const match = () => ({

export const replace = () => ({
'if (__a) __b': ({__a, __b}) => {
if (isConditionalExpression(__b))
return '__a && (__b)';

if (!isBlockStatement(__b))
return '__a && __b';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,8 @@ test('plugin-minify: convert-if-to-logical: transform: yield', (t) => {
t.transform('yield');
t.end();
});

test('plugin-minify: convert-if-to-logical: transform: nested', (t) => {
t.transform('nested');
t.end();
});
2 changes: 2 additions & 0 deletions packages/plugin-minify/test/fixture/if-fix.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
let a = 0;

Math.random() > 0.5 ? a++ : a--;

a && (b ? log('a and b are truthy') : log('a is truthy, b is falsy'));
6 changes: 6 additions & 0 deletions packages/plugin-minify/test/fixture/if.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,9 @@ if (Math.random() > 0.5)
else
a--;

if (a)
if (b)
log('a and b are truthy');
else
log('a is truthy, b is falsy');

0 comments on commit c4438f7

Please sign in to comment.