From 87285ed984535a152a63e4ca6c047dbf8cae25af Mon Sep 17 00:00:00 2001 From: jessicaquynh Date: Wed, 12 Oct 2016 01:14:45 -0400 Subject: [PATCH] tools: avoid let in for loops This adds a new ESLint tool to check for let declarations within the for, forIn, forOf expressions. Fixes: https://github.com/nodejs/node/issues/9045 Ref: https://github.com/nodejs/node/pull/8873 PR-URL: https://github.com/nodejs/node/pull/9049 Reviewed-By: Rich Trott Reviewed-By: Myles Borins Reviewed-By: Teddy Katz Reviewed-By: Prince John Wesley Reviewed-By: James M Snell --- lib/.eslintrc | 1 + .../eslint-rules/no-let-in-for-declaration.js | 46 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 tools/eslint-rules/no-let-in-for-declaration.js diff --git a/lib/.eslintrc b/lib/.eslintrc index 8fb98b7c180458..d8e34f85b5759d 100644 --- a/lib/.eslintrc +++ b/lib/.eslintrc @@ -2,3 +2,4 @@ rules: # Custom rules in tools/eslint-rules require-buffer: 2 buffer-constructor: 2 + no-let-in-for-declaration: 2 diff --git a/tools/eslint-rules/no-let-in-for-declaration.js b/tools/eslint-rules/no-let-in-for-declaration.js new file mode 100644 index 00000000000000..8b1a6783e0773d --- /dev/null +++ b/tools/eslint-rules/no-let-in-for-declaration.js @@ -0,0 +1,46 @@ +/** + * @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 +//------------------------------------------------------------------------------ + +module.exports = { + create(context) { + + 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.init, msg); + } + } + + /** + * 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.left, msg); + } + } + + return { + 'ForStatement': testForLoop, + 'ForInStatement': testForInOfLoop, + 'ForOfStatement': testForInOfLoop + }; + } +};