Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
feat(eslint-plugin): add new rule no-for-in-array#155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
8 commits Select commitHold shift + click to select a range
5ff29cd
feat(eslint-plugin): add new rule no-for-in-array
7d9991e
chore(eslint-plugin): remove unnecessary typedefs
a333448
chore: fix README spacing
767a62f
Merge branch 'master' into noForIn
j-f156fa66e
Update roadmap
j-f1d532334
fix: respond to review
7582ab0
Merge branch 'master' into noForIn
uniqueiniquity64906c1
Merge branch 'master' into noForIn
JamesHenryFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
1 change: 1 addition & 0 deletionspackages/eslint-plugin/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
12 changes: 9 additions & 3 deletionspackages/eslint-plugin/ROADMAP.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletionspackages/eslint-plugin/docs/rules/no-for-in-array.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# Disallow iterating over an array with a for-in loop (no-for-in-array) | ||
This rule prohibits iterating over an array with a for-in loop. | ||
## Rule Details | ||
Rationale from TSLint: | ||
A for-in loop (`for (var k in o)`) iterates over the properties of an Object. | ||
While it is legal to use for-in loops with array types, it is not common. | ||
for-in will iterate over the indices of the array as strings, omitting any "holes" in | ||
the array. | ||
More common is to use for-of, which iterates over the values of an array. | ||
If you want to iterate over the indices, alternatives include: | ||
```js | ||
array.forEach((value, index) => { ... }); | ||
for (const [index, value] of array.entries()) { ... } | ||
for (let i = 0; i < array.length; i++) { ... } | ||
``` | ||
Examples of **incorrect** code for this rule: | ||
```js | ||
for (const x in [3, 4, 5]) { | ||
console.log(x); | ||
} | ||
``` | ||
Examples of **correct** code for this rule: | ||
```js | ||
for (const x in { a: 3, b: 4, c: 5 }) { | ||
console.log(x); | ||
} | ||
``` | ||
## When Not To Use It | ||
If you want to iterate through a loop using the indices in an array as strings, you can turn off this rule. | ||
## Related to | ||
- TSLint: ['no-for-in-array'](https://palantir.github.io/tslint/rules/no-for-in-array/) |
56 changes: 56 additions & 0 deletionspackages/eslint-plugin/lib/rules/no-for-in-array.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
/** | ||
* @fileoverview Disallow iterating over an array with a for-in loop | ||
* @author Benjamin Lichtman | ||
*/ | ||
'use strict'; | ||
const ts = require('typescript'); | ||
const util = require('../util'); | ||
//------------------------------------------------------------------------------ | ||
// Rule Definition | ||
//------------------------------------------------------------------------------ | ||
/** | ||
* @type {import("eslint").Rule.RuleModule} | ||
*/ | ||
module.exports = { | ||
meta: { | ||
docs: { | ||
description: 'Disallow iterating over an array with a for-in loop', | ||
category: 'Functionality', | ||
recommended: false, | ||
extraDescription: [util.tslintRule('no-for-in-array')], | ||
url: util.metaDocsUrl('no-for-in-array') | ||
}, | ||
fixable: null, | ||
messages: { | ||
forInViolation: | ||
'For-in loops over arrays are forbidden. Use for-of or array.forEach instead.' | ||
}, | ||
schema: [], | ||
type: 'problem' | ||
}, | ||
create(context) { | ||
return { | ||
ForInStatement(node) { | ||
const parserServices = util.getParserServices(context); | ||
const checker = parserServices.program.getTypeChecker(); | ||
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node); | ||
const type = checker.getTypeAtLocation(originalNode.expression); | ||
if ( | ||
(typeof type.symbol !== 'undefined' && | ||
type.symbol.name === 'Array') || | ||
(type.flags & ts.TypeFlags.StringLike) !== 0 | ||
) { | ||
context.report({ | ||
node, | ||
messageId: 'forInViolation' | ||
}); | ||
} | ||
} | ||
}; | ||
} | ||
}; |
2 changes: 1 addition & 1 deletionpackages/eslint-plugin/lib/util.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletionspackages/eslint-plugin/tests/lib/rules/no-for-in-array.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
/** | ||
* @fileoverview Disallow iterating over an array with a for-in loop | ||
* @author Benjamin Lichtman | ||
*/ | ||
'use strict'; | ||
//------------------------------------------------------------------------------ | ||
// Requirements | ||
//------------------------------------------------------------------------------ | ||
const rule = require('../../../lib/rules/no-for-in-array'), | ||
RuleTester = require('eslint').RuleTester, | ||
path = require('path'); | ||
//------------------------------------------------------------------------------ | ||
// Tests | ||
//------------------------------------------------------------------------------ | ||
const rootDir = path.join(process.cwd(), 'tests/fixtures/'); | ||
const parserOptions = { | ||
ecmaVersion: 2015, | ||
tsconfigRootDir: rootDir, | ||
project: './tsconfig.json' | ||
}; | ||
const ruleTester = new RuleTester({ | ||
parserOptions, | ||
parser: '@typescript-eslint/parser' | ||
}); | ||
ruleTester.run('no-for-in-array', rule, { | ||
valid: [ | ||
` | ||
for (const x of [3, 4, 5]) { | ||
console.log(x); | ||
}`, | ||
` | ||
for (const x in { a: 1, b: 2, c: 3 }) { | ||
console.log(x); | ||
}` | ||
], | ||
invalid: [ | ||
{ | ||
code: ` | ||
for (const x in [3, 4, 5]) { | ||
console.log(x); | ||
}`, | ||
errors: [ | ||
{ | ||
messageId: 'forInViolation', | ||
type: 'ForInStatement' | ||
} | ||
] | ||
}, | ||
{ | ||
code: ` | ||
const z = [3, 4, 5]; | ||
for (const x in z) { | ||
console.log(x); | ||
}`, | ||
errors: [ | ||
{ | ||
messageId: 'forInViolation', | ||
type: 'ForInStatement' | ||
} | ||
] | ||
} | ||
] | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.