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 165ecad
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
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
37 changes: 36 additions & 1 deletion test/no-for-loop.js
Expand Up @@ -482,7 +482,42 @@ 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 165ecad

Please sign in to comment.