Skip to content

Commit

Permalink
fix: avoid naming collision with default array element variable in au…
Browse files Browse the repository at this point in the history
…tofix for `no-for-loop` rule
  • Loading branch information
bmish committed May 25, 2020
1 parent cec3a9d commit ae3e0bb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
3 changes: 2 additions & 1 deletion rules/no-for-loop.js
Expand Up @@ -2,6 +2,7 @@
const getDocumentationUrl = require('./utils/get-documentation-url');
const isLiteralValue = require('./utils/is-literal-value');
const {flatten} = require('lodash');
const avoidCapture = require('./utils/avoid-capture');

const defaultElementName = 'element';
const isLiteralZero = node => isLiteralValue(node, 0);
Expand Down Expand Up @@ -335,7 +336,7 @@ const create = context => {
const shouldGenerateIndex = isIndexVariableUsedElsewhereInTheLoopBody(indexVariable, bodyScope, arrayIdentifierName);

const index = indexIdentifierName;
const element = elementIdentifierName || defaultElementName;
const element = elementIdentifierName || avoidCapture(defaultElementName, [bodyScope], context.parserOptions.ecmaVersion);
const array = arrayIdentifierName;

let declarationElement = element;
Expand Down
34 changes: 34 additions & 0 deletions test/no-for-loop.js
Expand Up @@ -482,6 +482,40 @@ ruleTester.run('no-for-loop', rule, {
const [ a, b ] = element;
console.log(a, b, element);
}
`),

// Avoid naming collision when using default element name.
testCase(outdent`
for (let i = 0; i < arr.length; i += 1) {
console.log(arr[i]);
const element = foo();
console.log(element);
}
`, outdent`
for (const element_ of arr) {
console.log(element_);
const element = foo();
console.log(element);
}
`),

// Avoid naming collision when using default element name (multiple collisions).
testCase(outdent`
for (let i = 0; i < arr.length; i += 1) {
console.log(arr[i]);
const element = foo();
const element_ = foo();
console.log(element);
console.log(element_);
}
`, outdent`
for (const element__ of arr) {
console.log(element__);
const element = foo();
const element_ = foo();
console.log(element);
console.log(element_);
}
`)
]
});
Expand Down

0 comments on commit ae3e0bb

Please sign in to comment.