|
| 1 | +import { TSESTree, AST_NODE_TYPES } from "@typescript-eslint/utils"; |
| 2 | +import { Scope } from "@typescript-eslint/utils/ts-eslint"; |
| 3 | +import createRule from "../utils/createRule.js"; |
| 4 | + |
| 5 | +const noRepeatedMemberAccess = createRule({ |
| 6 | + name: "no-repeated-member-access", |
| 7 | + meta: { |
| 8 | + type: "suggestion", |
| 9 | + docs: { |
| 10 | + description: |
| 11 | + "Optimize repeated member access patterns by extracting variables", |
| 12 | + }, |
| 13 | + fixable: "code", |
| 14 | + schema: [ |
| 15 | + { |
| 16 | + type: "object", |
| 17 | + properties: { |
| 18 | + minOccurrences: { type: "number", minimum: 2, default: 3 }, |
| 19 | + }, |
| 20 | + }, |
| 21 | + ], |
| 22 | + messages: { |
| 23 | + repeatedAccess: |
| 24 | + "Member chain '{{ chain }}' accessed {{ count }} times. Extract to variable.", |
| 25 | + }, |
| 26 | + }, |
| 27 | + defaultOptions: [{ minOccurrences: 3 }], |
| 28 | + |
| 29 | + create(context, [options]) { |
| 30 | + const sourceCode = context.sourceCode; |
| 31 | + const minOccurrences = options.minOccurrences; |
| 32 | + |
| 33 | + type scopeKey = [Scope.Scope, TSESTree.MemberExpression[]]; |
| 34 | + type scopeValue = { count: number; modified: boolean }; |
| 35 | + const scopeMap = new WeakMap<scopeKey, scopeValue>(); |
| 36 | + // ====================== |
| 37 | + // Rule Listeners |
| 38 | + // ====================== |
| 39 | + // These event handlers process different AST node types and track chain usage |
| 40 | + // |
| 41 | + // Examples of what each listener detects: |
| 42 | + // - MemberExpression: obj.prop.val |
| 43 | + // - AssignmentExpression: obj.prop.val = 5 |
| 44 | + // - UpdateExpression: obj.prop.val++ |
| 45 | + // - CallExpression: obj.prop.method() |
| 46 | + return { |
| 47 | + // Track assignment expression |
| 48 | + // Example: obj.prop.val = 5 |
| 49 | + AssignmentExpression: (node) => { |
| 50 | + // track left expression and mark all of them to be modified |
| 51 | + }, |
| 52 | + |
| 53 | + // Track increment/decrement operations |
| 54 | + // Example: obj.prop.counter++ modifies "obj.prop.counter" |
| 55 | + UpdateExpression: (node) => { |
| 56 | + // track expression and mark all of them to be modified |
| 57 | + }, |
| 58 | + |
| 59 | + // Track function calls that might modify their arguments |
| 60 | + // Example: obj.methods.update() might modify the "obj.methods" chain |
| 61 | + CallExpression: (node) => { |
| 62 | + // track expression and mark all of them to be modified |
| 63 | + }, |
| 64 | + |
| 65 | + // Process member expressions to identify repeated patterns |
| 66 | + // Example: Catches obj.prop.val, user.settings.theme, etc. |
| 67 | + MemberExpression: (node) => processMemberExpression(node), |
| 68 | + }; |
| 69 | + }, |
| 70 | +}); |
| 71 | + |
| 72 | +export default noRepeatedMemberAccess; |
0 commit comments