Skip to content

Commit acd9379

Browse files
committed
fix(un-variable-merging): should not split varaible declration in for init that was actually used
1 parent 22ad078 commit acd9379

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

packages/unminify/src/transformations/__tests__/un-variable-merging.spec.ts

+8
Original file line numberDiff line numberDiff line change
@@ -59,12 +59,20 @@ inlineTest('variable declaration that is not used in for statement should not be
5959
for (var i = 0, j = 0, k = 0; j < 10; k++) {
6060
console.log(k);
6161
}
62+
63+
for (var _len = arguments.length, _arguments = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
64+
_arguments[_key - 2] = arguments[_key];
65+
}
6266
`,
6367
`
6468
var i = 0;
6569
for (var j = 0, k = 0; j < 10; k++) {
6670
console.log(k);
6771
}
72+
73+
for (var _len = arguments.length, _arguments = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
74+
_arguments[_key - 2] = arguments[_key];
75+
}
6876
`,
6977
)
7078

packages/unminify/src/transformations/un-variable-merging.ts

+7-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { mergeComments } from '@wakaru/ast-utils/comments'
22
import { replaceWithMultipleStatements } from '@wakaru/ast-utils/insert'
3+
import { findReferences } from '@wakaru/ast-utils/reference'
34
import { createJSCodeshiftTransformationRule } from '@wakaru/shared/rule'
45
import type { ASTTransformation } from '@wakaru/shared/rule'
56
import type { ForStatement } from 'jscodeshift'
@@ -32,23 +33,21 @@ export const transformAST: ASTTransformation = (context) => {
3233
.find(j.VariableDeclaration)
3334
.forEach((p) => {
3435
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
3637
if (init && j.VariableDeclaration.check(init) && init.kind === 'var') {
3738
const initDeclarators = init.declarations
3839
// 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
4142

42-
const { id } = d
43+
const { id } = declarator
4344
if (!j.Identifier.check(id)) return false
4445

4546
// check if the name is declared outside of the for statement
4647
if (p.parent?.parent?.scope.lookup(id.name)) return true
4748

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
5251

5352
return false
5453
})

0 commit comments

Comments
 (0)