Skip to content

Commit

Permalink
feat: split variable declarations in for loop (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
kuizuo authored Jan 2, 2024
1 parent 38f0165 commit b8d32a4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,42 @@ test('split exported variable declarations', () =>
export const c = 3;
`));

test('dont split in for loop', () =>
test('split var in for loop initializer', () =>
expectJS(`
for (let i = 0, j = 1; i < 10; i++, j++) var a, b;
for (var i = 0, j = 1;;) {}
`).toMatchInlineSnapshot(`
for (let i = 0, j = 1; i < 10; i++, j++) {
var i = 0;
var j = 1;
for (;;) {}
`));

test('ignore let in for loop initializer', () => {
expectJS(`
let i;
for (let i = 0, j = 1;;) {}
`).toMatchInlineSnapshot(`
let i;
for (let i = 0, j = 1;;) {}
`);

expectJS(`
for (let i = 0, j = 1;;) {
setTimeout(() => console.log(i));
if (++i > 3) break;
}
`).toMatchInlineSnapshot(`
for (let i = 0, j = 1;;) {
setTimeout(() => console.log(i));
if (++i > 3) break;
}
`);
});

test('ignore for loop with test or update', () =>
expectJS(`
for (var i = 0, j = 1; i < 10; i++, j++) var a, b;
`).toMatchInlineSnapshot(`
for (var i = 0, j = 1; i < 10; i++, j++) {
var a;
var b;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,40 @@ export default {
visitor: () => ({
VariableDeclaration: {
exit(path) {
if (path.node.declarations.length > 1 && path.key !== 'init') {
if (path.parentPath.isExportNamedDeclaration()) {
path.parentPath.replaceWithMultiple(
path.node.declarations.map((declaration) =>
t.exportNamedDeclaration(
if (path.node.declarations.length > 1) {
// E.g. for (var i = 0, j = 1;;)
if (path.key === 'init' && path.parentPath.isForStatement()) {
if (
!path.parentPath.node.test &&
!path.parentPath.node.update &&
path.node.kind === 'var'
) {
path.parentPath.insertBefore(
path.node.declarations.map((declaration) =>
t.variableDeclaration(path.node.kind, [declaration]),
),
),
);
);
path.remove();
this.changes++;
}
} else {
path.replaceWithMultiple(
path.node.declarations.map((declaration) =>
t.variableDeclaration(path.node.kind, [declaration]),
),
);
if (path.parentPath.isExportNamedDeclaration()) {
path.parentPath.replaceWithMultiple(
path.node.declarations.map((declaration) =>
t.exportNamedDeclaration(
t.variableDeclaration(path.node.kind, [declaration]),
),
),
);
} else {
path.replaceWithMultiple(
path.node.declarations.map((declaration) =>
t.variableDeclaration(path.node.kind, [declaration]),
),
);
}
this.changes++;
}
this.changes++;
}
},
},
Expand Down

0 comments on commit b8d32a4

Please sign in to comment.