Skip to content

Commit

Permalink
Allow redeclaration of loop variable in body (#11088)
Browse files Browse the repository at this point in the history
  • Loading branch information
openorclose committed Feb 11, 2020
1 parent 865d515 commit 3907396
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 4 deletions.
19 changes: 15 additions & 4 deletions packages/babel-plugin-transform-for-of/src/index.js
Expand Up @@ -19,7 +19,7 @@ export default declare((api, options) => {
visitor: {
ForOfStatement(path) {
const { scope } = path;
const { left, right, body, await: isAwait } = path.node;
const { left, right, await: isAwait } = path.node;
if (isAwait) {
return;
}
Expand Down Expand Up @@ -48,8 +48,19 @@ export default declare((api, options) => {
);
}

const block = t.toBlock(body);
block.body.unshift(assignment);
let blockBody;
const body = path.get("body");
if (
body.isBlockStatement() &&
Object.keys(path.getBindingIdentifiers()).some(id =>
body.scope.hasOwnBinding(id),
)
) {
blockBody = t.blockStatement([assignment, body.node]);
} else {
blockBody = t.toBlock(body.node);
blockBody.body.unshift(assignment);
}

path.replaceWith(
t.forStatement(
Expand All @@ -60,7 +71,7 @@ export default declare((api, options) => {
t.memberExpression(t.cloneNode(array), t.identifier("length")),
),
t.updateExpression("++", t.cloneNode(i)),
block,
blockBody,
),
);
},
Expand Down
@@ -0,0 +1,5 @@
for (const [head, ...tail] of array) {
const head = 1;
console.log(tail);
console.log(head);
}
@@ -0,0 +1,8 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const [head, ...tail] = _array[_i];
{
const head = 1;
console.log(tail);
console.log(head);
}
}
@@ -0,0 +1,5 @@
for (const [type, ...rest] of array) {
const type = 1;
console.log(rest);
console.log(type);
}
@@ -0,0 +1,8 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const [type, ...rest] = _array[_i];
{
const type = 1;
console.log(rest);
console.log(type);
}
}
@@ -0,0 +1,6 @@
for (const [head, ...tail] of array) {
const head = 1;
let tail;
console.log(tail);
console.log(head);
}
@@ -0,0 +1,9 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const [head, ...tail] = _array[_i];
{
const head = 1;
let tail;
console.log(tail);
console.log(head);
}
}
@@ -0,0 +1,6 @@
for (const {type, ...rest} of array) {
const type = 1;
let rest;
console.log(rest);
console.log(type);
}
@@ -0,0 +1,12 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const {
type,
...rest
} = _array[_i];
{
const type = 1;
let rest;
console.log(rest);
console.log(type);
}
}
@@ -0,0 +1,3 @@
for (const elm of array) {
const elm = 2;
}
@@ -0,0 +1,6 @@
for (let _i = 0, _array = array; _i < _array.length; _i++) {
const elm = _array[_i];
{
const elm = 2;
}
}

0 comments on commit 3907396

Please sign in to comment.