Skip to content

Commit

Permalink
feat: transform for loop to while loop
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Dec 29, 2023
1 parent 1c6d171 commit b9180a0
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
12 changes: 12 additions & 0 deletions apps/docs/src/concepts/unminify.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ console["log"](a); // [!code --]
console.log(a); // [!code ++]
```

## for-to-while

```js
for (;;) a(); // [!code --]
while (true) a(); // [!code ++]
```

```js
for (; a < b;) c(); // [!code --]
while (a < b) c(); // [!code ++]
```

## infinity

```js
Expand Down
20 changes: 20 additions & 0 deletions packages/webcrack/src/unminify/test/for-to-while.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { test } from 'vitest';
import { testTransform } from '../../../test';
import forToWhile from '../transforms/for-to-while';

const expectJS = testTransform(forToWhile);

test('empty for loop to while true', () =>
expectJS(`for (;;) b()`).toMatchInlineSnapshot(`while (true) b();`));

test('for loop with only test to while', () =>
expectJS(`for (; a(); ) b();`).toMatchInlineSnapshot(`while (a()) b();`));

test('ignore for loop with init or update', () =>
expectJS(`
for (let i = 0;;) {}
for (;; i++) {}
`).toMatchInlineSnapshot(`
for (let i = 0;;) {}
for (;; i++) {}
`));
23 changes: 23 additions & 0 deletions packages/webcrack/src/unminify/transforms/for-to-while.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as t from '@babel/types';
import { Transform } from '../../ast-utils';

export default {
name: 'for-to-while',
tags: ['safe'],
visitor() {
return {
ForStatement: {
exit(path) {
const { test, body, init, update } = path.node;
if (init || update) return;
path.replaceWith(
test
? t.whileStatement(test, body)
: t.whileStatement(t.booleanLiteral(true), body),
);
this.changes++;
},
},
};
},
} satisfies Transform;
1 change: 1 addition & 0 deletions packages/webcrack/src/unminify/transforms/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { default as blockStatements } from './block-statements';
export { default as computedProperties } from './computed-properties';
export { default as forToWhile } from './for-to-while';
export { default as infinity } from './infinity';
export { default as invertBooleanLogic } from './invert-boolean-logic';
export { default as jsonParse } from './json-parse';
Expand Down

0 comments on commit b9180a0

Please sign in to comment.