Skip to content

Commit

Permalink
move code to util
Browse files Browse the repository at this point in the history
  • Loading branch information
kirkwaiblinger committed Apr 7, 2024
1 parent 4c65fcc commit 0e407fe
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 19 deletions.
21 changes: 2 additions & 19 deletions packages/eslint-plugin/src/rules/no-for-in-array.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import type { TSESTree } from '@typescript-eslint/utils';
import * as ts from 'typescript';

import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
isTypeArrayTypeOrUnionOfArrayTypes,
nullThrows,
} from '../util';
import { getForStatementHeadLoc } from '../util/getForStatementHeadLoc';

export default createRule({
name: 'no-for-in-array',
Expand All @@ -26,22 +25,6 @@ export default createRule({
},
defaultOptions: [],
create(context) {
function getReportLoc(
forInNode: TSESTree.ForInStatement,
): TSESTree.SourceLocation {
const closingParens = nullThrows(
context.sourceCode.getTokenBefore(
forInNode.body,
token => token.value === ')',
),
'for-in must have a closing parenthesis.',
);
return {
start: structuredClone(forInNode.loc.start),
end: structuredClone(closingParens.loc.end),
};
}

return {
ForInStatement(node): void {
const services = getParserServices(context);
Expand All @@ -54,7 +37,7 @@ export default createRule({
(type.flags & ts.TypeFlags.StringLike) !== 0
) {
context.report({
loc: getReportLoc(node),
loc: getForStatementHeadLoc(context.sourceCode, node),
messageId: 'forInViolation',
});
}
Expand Down
34 changes: 34 additions & 0 deletions packages/eslint-plugin/src/util/getForStatementHeadLoc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { nullThrows } from '@typescript-eslint/utils/eslint-utils';

/**
* Gets the location of the head of the given for statement variant for reporting.
*
* - `for (const foo in bar) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^
*
* - `for (const foo of bar) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^
*
* - `for await (const foo of bar) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*
* - `for (let i = 0; i < 10; i++) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/
export function getForStatementHeadLoc(
sourceCode: TSESLint.SourceCode,
node:
| TSESTree.ForInStatement
| TSESTree.ForOfStatement
| TSESTree.ForStatement,
): TSESTree.SourceLocation {
const closingParens = nullThrows(
sourceCode.getTokenBefore(node.body, token => token.value === ')'),
'for statement must have a closing parenthesis.',
);
return {
start: structuredClone(node.loc.start),
end: structuredClone(closingParens.loc.end),
};
}

0 comments on commit 0e407fe

Please sign in to comment.