Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Commit

Permalink
Fix false positive in prefer-for-of when array is in parentheses (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
nchen63 authored and adidahiya committed Jan 5, 2017
1 parent 9bb5d28 commit b20dfce
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/rules/preferForOfRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import * as ts from "typescript";
import * as Lint from "../index";
import { isAssignment } from "../language/utils";
import { isAssignment, unwrapParentheses } from "../language/utils";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
Expand Down Expand Up @@ -100,7 +100,7 @@ class PreferForOfWalker extends Lint.BlockScopeAwareRuleWalker<{}, IncrementorMa
// check if iterator is used for something other than reading data from array
if (node.parent != null && node.parent.kind === ts.SyntaxKind.ElementAccessExpression) {
const elementAccess = node.parent as ts.ElementAccessExpression;
const arrayIdentifier = elementAccess.expression as ts.Identifier;
const arrayIdentifier = unwrapParentheses(elementAccess.expression) as ts.Identifier;
if (incrementorState.arrayToken.text !== arrayIdentifier.text) {
// iterator used in array other than one iterated over
incrementorState.onlyArrayReadAccess = false;
Expand Down Expand Up @@ -155,7 +155,7 @@ class PreferForOfWalker extends Lint.BlockScopeAwareRuleWalker<{}, IncrementorMa
if (conditionRight.kind === ts.SyntaxKind.PropertyAccessExpression) {
const propertyAccess = conditionRight as ts.PropertyAccessExpression;
if (indexVariable != null && propertyAccess.name.getText() === "length") {
return { indexVariable: indexVariable!, arrayToken: propertyAccess.expression };
return { indexVariable: indexVariable!, arrayToken: unwrapParentheses(propertyAccess.expression) };
}
}

Expand Down
6 changes: 6 additions & 0 deletions test/rules/prefer-for-of/test.ts.lint
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
function sampleFunc() {
// issue #1931, should not error
const value1 = [1];
const value2 = [2];
for (let i = 0; i < (value1).length; i++) {
const x = (value1)[i] === (value2)[i];
}

// This loop only uses the iterator to access the array item, so we can recommend a for-of loop here
for (var a = 0; a < obj.arr.length; a++) {
Expand Down

0 comments on commit b20dfce

Please sign in to comment.