From 258ddb0708b7a44959bd3ac399cbde912c8021c8 Mon Sep 17 00:00:00 2001 From: Armano Date: Wed, 24 Nov 2021 00:49:02 +0100 Subject: [PATCH] fix(eslint-plugin): [prefer-for-of] do nor error when iterating over this (#4176) * fix(eslint-plugin): [prefer-for-of] do not error when used on this expression * fix(eslint-plugin): [prefer-for-of] add missing test case * fix(eslint-plugin): [prefer-for-of] do nor error when iterating over this --- .../eslint-plugin/src/rules/prefer-for-of.ts | 1 + .../tests/rules/prefer-for-of.test.ts | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/packages/eslint-plugin/src/rules/prefer-for-of.ts b/packages/eslint-plugin/src/rules/prefer-for-of.ts index e1c3a058016..453d126c813 100644 --- a/packages/eslint-plugin/src/rules/prefer-for-of.ts +++ b/packages/eslint-plugin/src/rules/prefer-for-of.ts @@ -174,6 +174,7 @@ export default util.createRule({ !contains(body, id) || (node !== undefined && node.type === AST_NODE_TYPES.MemberExpression && + node.object.type !== AST_NODE_TYPES.ThisExpression && node.property === id && sourceCode.getText(node.object) === arrayText && !isAssignee(node)) diff --git a/packages/eslint-plugin/tests/rules/prefer-for-of.test.ts b/packages/eslint-plugin/tests/rules/prefer-for-of.test.ts index d2d7319b3b1..02c7d6478f0 100644 --- a/packages/eslint-plugin/tests/rules/prefer-for-of.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-for-of.test.ts @@ -180,6 +180,16 @@ for (var c = 0; c < arr.length; c++) { ` for (var d = 0; d < arr.length; d++) doMath?.(d); `, + ` +for (let i = 0; i < test.length; ++i) { + this[i]; +} + `, + ` +for (let i = 0; i < this.length; ++i) { + yield this[i]; +} + `, ], invalid: [ { @@ -357,6 +367,30 @@ for (let i = 0; i < arr.length; i++) { code: ` for (let i = 0; i < arr.length; i++) { ({ foo: obj[arr[i]] } = { foo: 1 }); +} + `, + errors: [ + { + messageId: 'preferForOf', + }, + ], + }, + { + code: ` +for (let i = 0; i < this.item.length; ++i) { + this.item[i]; +} + `, + errors: [ + { + messageId: 'preferForOf', + }, + ], + }, + { + code: ` +for (let i = 0; i < this.array.length; ++i) { + yield this.array[i]; } `, errors: [