From d3c2334646eae9287d5be9e457d041e445efb512 Mon Sep 17 00:00:00 2001 From: David Waller Date: Sat, 14 Sep 2019 03:03:56 +0200 Subject: [PATCH] Update: flag nested block with declaration as error (#12193) --- lib/rules/no-lone-blocks.js | 7 +++++- tests/lib/rules/no-lone-blocks.js | 36 ++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/lib/rules/no-lone-blocks.js b/lib/rules/no-lone-blocks.js index 6b51795863b..4365b047861 100644 --- a/lib/rules/no-lone-blocks.js +++ b/lib/rules/no-lone-blocks.js @@ -79,7 +79,7 @@ module.exports = { } }; - // ES6: report blocks without block-level bindings + // ES6: report blocks without block-level bindings, or that's only child of another block if (context.parserOptions.ecmaVersion >= 6) { ruleDef = { BlockStatement(node) { @@ -91,6 +91,11 @@ module.exports = { if (loneBlocks.length > 0 && loneBlocks[loneBlocks.length - 1] === node) { loneBlocks.pop(); report(node); + } else if ( + node.parent.type === "BlockStatement" && + node.parent.body.length === 1 + ) { + report(node); } } }; diff --git a/tests/lib/rules/no-lone-blocks.js b/tests/lib/rules/no-lone-blocks.js index 3640a10127f..139e24c9d04 100644 --- a/tests/lib/rules/no-lone-blocks.js +++ b/tests/lib/rules/no-lone-blocks.js @@ -56,7 +56,8 @@ ruleTester.run("no-lone-blocks", rule, { baz; } } - ` + `, + { code: "function foo() { { const x = 4 } const x = 3 }", parserOptions: { ecmaVersion: 6 } } ], invalid: [ { code: "{}", errors: [{ message: "Block is redundant.", type: "BlockStatement" }] }, @@ -118,6 +119,39 @@ ruleTester.run("no-lone-blocks", rule, { } `, errors: [{ message: "Block is redundant.", type: "BlockStatement", line: 4 }] + }, + { + code: ` + function foo () { + { + const x = 4; + } + } + `, + parserOptions: { ecmaVersion: 6 }, + errors: [ + { + message: "Nested block is redundant.", + type: "BlockStatement", + line: 3 + } + ] + }, + { + code: ` + function foo () { + { + var x = 4; + } + } + `, + errors: [ + { + message: "Nested block is redundant.", + type: "BlockStatement", + line: 3 + } + ] } ] });