|
1 | 1 | import { mergeComments } from '@wakaru/ast-utils/comments'
|
2 | 2 | import { replaceWithMultipleStatements } from '@wakaru/ast-utils/insert'
|
| 3 | +import { findReferences } from '@wakaru/ast-utils/reference' |
3 | 4 | import { createJSCodeshiftTransformationRule } from '@wakaru/shared/rule'
|
4 | 5 | import type { ASTTransformation } from '@wakaru/shared/rule'
|
5 | 6 | import type { ForStatement } from 'jscodeshift'
|
@@ -32,23 +33,21 @@ export const transformAST: ASTTransformation = (context) => {
|
32 | 33 | .find(j.VariableDeclaration)
|
33 | 34 | .forEach((p) => {
|
34 | 35 | if (j.ForStatement.check(p.parent.node)) {
|
35 |
| - const { init, test, update } = p.parent.node as ForStatement |
| 36 | + const { init } = p.parent.node as ForStatement |
36 | 37 | if (init && j.VariableDeclaration.check(init) && init.kind === 'var') {
|
37 | 38 | const initDeclarators = init.declarations
|
38 | 39 | // filter out the declarations that are used in test or update
|
39 |
| - const usedDeclarators = initDeclarators.filter((d) => { |
40 |
| - if (!j.VariableDeclarator.check(d)) return false |
| 40 | + const usedDeclarators = initDeclarators.filter((declarator) => { |
| 41 | + if (!j.VariableDeclarator.check(declarator)) return false |
41 | 42 |
|
42 |
| - const { id } = d |
| 43 | + const { id } = declarator |
43 | 44 | if (!j.Identifier.check(id)) return false
|
44 | 45 |
|
45 | 46 | // check if the name is declared outside of the for statement
|
46 | 47 | if (p.parent?.parent?.scope.lookup(id.name)) return true
|
47 | 48 |
|
48 |
| - const name = id.name |
49 |
| - const isUsedInTest = test && j(test).find(j.Identifier, { name }).size() > 0 |
50 |
| - const isUsedInUpdate = update && j(update).find(j.Identifier, { name }).size() > 0 |
51 |
| - if (isUsedInTest || isUsedInUpdate) return true |
| 49 | + const isUsed = findReferences(j, p.parent, id.name).size() > 1 |
| 50 | + if (isUsed) return true |
52 | 51 |
|
53 | 52 | return false
|
54 | 53 | })
|
|
0 commit comments