|
11 | 11 | //------------------------------------------------------------------------------ |
12 | 12 | // Rule Definition |
13 | 13 | //------------------------------------------------------------------------------ |
| 14 | +const message = 'Use of `let` as the loop variable in a for-loop is ' + |
| 15 | + 'not recommended. Please use `var` instead.'; |
| 16 | +const forSelector = 'ForStatement[init.kind="let"]'; |
| 17 | +const forInOfSelector = 'ForOfStatement[left.kind="let"],' + |
| 18 | + 'ForInStatement[left.kind="let"]'; |
14 | 19 |
|
15 | 20 | module.exports = { |
16 | 21 | create(context) { |
17 | 22 | const sourceCode = context.getSourceCode(); |
18 | | - const msg = 'Use of `let` as the loop variable in a for-loop is ' + |
19 | | - 'not recommended. Please use `var` instead.'; |
20 | | - |
21 | | - /** |
22 | | - * Report function to test if the for-loop is declared using `let`. |
23 | | - */ |
24 | | - function testForLoop(node) { |
25 | | - if (node.init && node.init.kind === 'let') { |
26 | | - context.report({ |
27 | | - node: node.init, |
28 | | - message: msg, |
29 | | - fix: (fixer) => |
30 | | - fixer.replaceText(sourceCode.getFirstToken(node.init), 'var') |
31 | | - }); |
32 | | - } |
33 | | - } |
34 | 23 |
|
35 | | - /** |
36 | | - * Report function to test if the for-in or for-of loop |
37 | | - * is declared using `let`. |
38 | | - */ |
39 | | - function testForInOfLoop(node) { |
40 | | - if (node.left && node.left.kind === 'let') { |
41 | | - context.report({ |
42 | | - node: node.left, |
43 | | - message: msg, |
44 | | - fix: (fixer) => |
45 | | - fixer.replaceText(sourceCode.getFirstToken(node.left), 'var') |
46 | | - }); |
47 | | - } |
| 24 | + function report(node) { |
| 25 | + context.report({ |
| 26 | + node, |
| 27 | + message, |
| 28 | + fix: (fixer) => |
| 29 | + fixer.replaceText(sourceCode.getFirstToken(node), 'var') |
| 30 | + }); |
48 | 31 | } |
49 | 32 |
|
50 | 33 | return { |
51 | | - 'ForStatement': testForLoop, |
52 | | - 'ForInStatement': testForInOfLoop, |
53 | | - 'ForOfStatement': testForInOfLoop |
| 34 | + [forSelector]: (node) => report(node.init), |
| 35 | + [forInOfSelector]: (node) => report(node.left), |
54 | 36 | }; |
55 | 37 | } |
56 | 38 | }; |
0 commit comments