Skip to content

Commit

Permalink
Fix element used case
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Dec 17, 2019
1 parent ca742cb commit c034799
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
27 changes: 20 additions & 7 deletions rules/no-for-loop.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,18 +326,27 @@ const create = context => {
const shouldGenerateIndex = isIndexVariableUsedElsewhereInTheLoopBody(indexVariable, bodyScope, arrayIdentifierName);

const index = indexIdentifierName;
const element = elementIdentifierName || defaultElementName;
const array = arrayIdentifierName;

let element = elementIdentifierName || defaultElementName;
let declarationElement = element;
let declarationType = 'const';
if (elementNode && elementNode.id.type === 'ObjectPattern') {
declarationType = elementNode.parent.kind;
element = sourceCode.getText(elementNode.id);
let removeDeclaration = true;
if (
elementNode &&
elementNode.id.type === 'ObjectPattern'
) {
removeDeclaration = arrayReferences.length === 1;

if (removeDeclaration) {
declarationType = elementNode.parent.kind;
declarationElement = sourceCode.getText(elementNode.id);
}
}

const replacement = shouldGenerateIndex ?
`${declarationType} [${index}, ${element}] of ${array}.entries()` :
`${declarationType} ${element} of ${array}`;
`${declarationType} [${index}, ${declarationElement}] of ${array}.entries()` :
`${declarationType} ${declarationElement} of ${array}`;

return [
fixer.replaceTextRange([
Expand All @@ -351,7 +360,11 @@ const create = context => {

return fixer.replaceText(reference.identifier.parent, element);
}),
elementNode && fixer.removeRange(getRemovalRange(elementNode, sourceCode))
elementNode && (
removeDeclaration ?
fixer.removeRange(getRemovalRange(elementNode, sourceCode)) :
fixer.replaceText(elementNode.init, element)
)
].filter(Boolean);
};
}
Expand Down
11 changes: 11 additions & 0 deletions test/no-for-loop.js
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,17 @@ ruleTester.run('no-for-loop', rule, {
for (var [i, { a, b }] of arr.entries()) {
console.log(i, a, b);
}
`),
testCase(outdent`
for (let i = 0; i < arr.length; i++) {
const { a, b } = arr[i];
console.log(a, b, i, arr[i]);
}
`, outdent`
for (const [i, element] of arr.entries()) {
const { a, b } = element;
console.log(a, b, i, element);
}
`)
]
});
Expand Down

0 comments on commit c034799

Please sign in to comment.