Skip to content

Commit

Permalink
feat: extract sequence from for-of
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Jul 10, 2024
1 parent e2e10b6 commit 2d7735a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
6 changes: 6 additions & 0 deletions apps/docs/src/concepts/unminify.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,12 @@ a = 1; // [!code ++]
for (let key in object) {} // [!code ++]
```

```js
for (let value of (a = 1, array)) {} // [!code --]
a = 1; // [!code ++]
for (let value of array) {} // [!code ++]
```

```js
for((a(), b());;) {} // [!code --]
a(); // [!code ++]
Expand Down
8 changes: 8 additions & 0 deletions packages/webcrack/src/unminify/test/sequence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ test('rearrange from for-in', () =>
for (let key in object) {}
`));

test('rearrange from for-of', () =>
expectJS(`
for (let value of (a = 1, array)) {}
`).toMatchInlineSnapshot(`
a = 1;
for (let value of array) {}
`));

test('rearrange from for loop init', () => {
expectJS(`
for((a(), b());;);
Expand Down
17 changes: 13 additions & 4 deletions packages/webcrack/src/unminify/transforms/sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,20 @@ export default {
},
ForInStatement: {
exit(path) {
const sequence = m.capture(m.sequenceExpression());
const matcher = m.forInStatement(m.anything(), sequence);
if (!matcher.match(path.node)) return;
if (!t.isSequenceExpression(path.node.right)) return;

const { expressions } = sequence.current!;
const { expressions } = path.node.right;
path.node.right = expressions.pop()!;
const statements = expressions.map(t.expressionStatement);
path.insertBefore(statements);
this.changes++;
},
},
ForOfStatement: {
exit(path) {
if (!t.isSequenceExpression(path.node.right)) return;

const { expressions } = path.node.right;
path.node.right = expressions.pop()!;
const statements = expressions.map(t.expressionStatement);
path.insertBefore(statements);
Expand Down

0 comments on commit 2d7735a

Please sign in to comment.