summaryrefslogtreecommitdiff
path: root/tools/eslint-rules/no-let-in-for-declaration.js
blob: 1ae49a48dee8a242ec0ca37e3e871e6c345d902f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * @fileoverview Prohibit the use of `let` as the loop variable
 *               in the initialization of for, and the left-hand
 *               iterator in forIn and forOf loops.
 *
 * @author Jessica Quynh Tran
 */

'use strict';

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const message = 'Use of `let` as the loop variable in a for-loop is ' +
                'not recommended. Please use `var` instead.';
const forSelector = 'ForStatement[init.kind="let"]';
const forInOfSelector = 'ForOfStatement[left.kind="let"],' +
                        'ForInStatement[left.kind="let"]';

module.exports = {
  create(context) {
    const sourceCode = context.getSourceCode();

    function report(node) {
      context.report({
        node,
        message,
        fix: (fixer) =>
          fixer.replaceText(sourceCode.getFirstToken(node), 'var')
      });
    }

    return {
      [forSelector]: (node) => report(node.init),
      [forInOfSelector]: (node) => report(node.left),
    };
  }
};