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

Commit

Permalink
prefer-for-of: identify more array modifications (#3044)
Browse files Browse the repository at this point in the history
  • Loading branch information
ajafff committed Jul 21, 2017
1 parent f9e162f commit a29ba47
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
15 changes: 6 additions & 9 deletions src/rules/preferForOfRule.ts
Expand Up @@ -18,7 +18,7 @@
import * as utils from "tsutils";
import * as ts from "typescript";
import * as Lint from "../index";
import { isAssignment, unwrapParentheses } from "../language/utils";
import { unwrapParentheses } from "../language/utils";

export class Rule extends Lint.Rules.AbstractRule {
/* tslint:disable:object-literal-sort-keys */
Expand Down Expand Up @@ -76,15 +76,12 @@ function walk(ctx: Lint.WalkContext<void>): void {

function isNonSimpleIncrementorUse(node: ts.Identifier, arrayExpr: ts.Expression, sourceFile: ts.SourceFile): boolean {
// check if iterator is used for something other than reading data from array
const elementAccess = node.parent!;
const accessParent = elementAccess.parent!;
return !utils.isElementAccessExpression(elementAccess)
// `a[i] = ...`
|| isAssignment(accessParent)
// `delete a[i]`
|| accessParent.kind === ts.SyntaxKind.DeleteExpression
const parent = node.parent!;
return !utils.isElementAccessExpression(parent)
// `a[i] = ...` or similar
|| utils.isReassignmentTarget(parent)
// `b[i]`
|| !nodeEquals(arrayExpr, unwrapParentheses(elementAccess.expression), sourceFile);
|| !nodeEquals(arrayExpr, unwrapParentheses(parent.expression), sourceFile);
}

function nodeEquals(a: ts.Node, b: ts.Node, sourceFile: ts.SourceFile): boolean {
Expand Down
16 changes: 16 additions & 0 deletions test/rules/prefer-for-of/test.ts.lint
Expand Up @@ -178,4 +178,20 @@ function test() {
print();
}

for (let i = 0; i < arr.length; ++i) {
arr[i]++;
}

for (let i = 0; i < arr.length; ++i) {
({...arr[i]} = foo);
}

for (let i = 0; i < arr.length; ++i) {
for (arr[i] of otherArr) {}
}

for (let i = 0; i < arr.length; ++i) {
++(arr[i]);
}

[0]: Expected a 'for-of' loop instead of a 'for' loop with this simple iteration

0 comments on commit a29ba47

Please sign in to comment.