-
Notifications
You must be signed in to change notification settings - Fork 142
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: transform for loop to while loop
- Loading branch information
Showing
4 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++) {} | ||
`)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters