Skip to content

Commit

Permalink
fix: requeue flipped paths in yoda
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Dec 29, 2023
1 parent b9180a0 commit aa262c0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
18 changes: 18 additions & 0 deletions packages/webcrack/src/unminify/test/unminify.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { test } from 'vitest';
import unminify from '..';
import { testTransform } from '../../../test';

const expectJS = testTransform(unminify);

test('mixed typeof-undefined and yoda', () =>
expectJS(`
typeof x < "u";
"u" > typeof x;
typeof x > "u";
"u" < typeof x;
`).toMatchInlineSnapshot(`
typeof x !== "undefined";
typeof x !== "undefined";
typeof x === "undefined";
typeof x === "undefined";
`));
20 changes: 13 additions & 7 deletions packages/webcrack/src/unminify/transforms/yoda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Transform } from '../../ast-utils';

// https://eslint.org/docs/latest/rules/yoda and https://babeljs.io/docs/en/babel-plugin-minify-flip-comparisons

const flippedOperators = {
const FLIPPED_OPERATORS = {
'==': '==',
'===': '===',
'!=': '!=',
Expand All @@ -24,7 +24,7 @@ export default {
tags: ['safe'],
visitor: () => {
const matcher = m.binaryExpression(
m.or(...Object.values(flippedOperators)),
m.or(...Object.values(FLIPPED_OPERATORS)),
m.or(
m.stringLiteral(),
m.numericLiteral(),
Expand All @@ -43,11 +43,17 @@ export default {

return {
BinaryExpression: {
exit({ node }) {
if (matcher.match(node)) {
[node.left, node.right] = [node.right, node.left as t.Expression];
node.operator =
flippedOperators[node.operator as keyof typeof flippedOperators];
exit(path) {
if (matcher.match(path.node)) {
path.replaceWith(
t.binaryExpression(
FLIPPED_OPERATORS[
path.node.operator as keyof typeof FLIPPED_OPERATORS
],
path.node.right,
path.node.left as t.Expression,
),
);
this.changes++;
}
},
Expand Down

0 comments on commit aa262c0

Please sign in to comment.