Skip to content

Commit

Permalink
tools: simplify no-let-in-for-declaration rule
Browse files Browse the repository at this point in the history
PR-URL: #17572
Reviewed-By: Anatoli Papirovski <apapirovski@mac.com>
  • Loading branch information
cjihrig authored and MylesBorins committed Dec 12, 2017
1 parent e157e1c commit f7a1e39
Showing 1 changed file with 14 additions and 32 deletions.
46 changes: 14 additions & 32 deletions tools/eslint-rules/no-let-in-for-declaration.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,46 +11,28 @@
//------------------------------------------------------------------------------
// 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();
const msg = 'Use of `let` as the loop variable in a for-loop is ' +
'not recommended. Please use `var` instead.';

/**
* Report function to test if the for-loop is declared using `let`.
*/
function testForLoop(node) {
if (node.init && node.init.kind === 'let') {
context.report({
node: node.init,
message: msg,
fix: (fixer) =>
fixer.replaceText(sourceCode.getFirstToken(node.init), 'var')
});
}
}

/**
* Report function to test if the for-in or for-of loop
* is declared using `let`.
*/
function testForInOfLoop(node) {
if (node.left && node.left.kind === 'let') {
context.report({
node: node.left,
message: msg,
fix: (fixer) =>
fixer.replaceText(sourceCode.getFirstToken(node.left), 'var')
});
}
function report(node) {
context.report({
node,
message,
fix: (fixer) =>
fixer.replaceText(sourceCode.getFirstToken(node), 'var')
});
}

return {
'ForStatement': testForLoop,
'ForInStatement': testForInOfLoop,
'ForOfStatement': testForInOfLoop
[forSelector]: (node) => report(node.init),
[forInOfSelector]: (node) => report(node.left),
};
}
};

0 comments on commit f7a1e39

Please sign in to comment.