2 * @fileoverview Rule to flag for-in loops without if statements inside
3 * @author Nicholas C. Zakas
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
17 description: "require `for-in` loops to include an `if` statement",
18 category: "Best Practices",
20 url: "https://eslint.org/docs/rules/guard-for-in"
25 wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."
33 ForInStatement(node) {
34 const body = node.body;
37 if (body.type === "EmptyStatement") {
42 if (body.type === "IfStatement") {
47 if (body.type === "BlockStatement" && body.body.length === 0) {
51 // block with just if statement
52 if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
56 // block that starts with if statement
57 if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
58 const i = body.body[0];
60 // ... whose consequent is a continue
61 if (i.consequent.type === "ContinueStatement") {
65 // ... whose consequent is a block that contains only a continue
66 if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
71 context.report({ node, messageId: "wrap" });