UNPKG

2.27 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag for-in loops without if statements inside
3 * @author Nicholas C. Zakas
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 docs: {
15 description: "require `for-in` loops to include an `if` statement",
16 category: "Best Practices",
17 recommended: false,
18 url: "https://eslint.org/docs/rules/guard-for-in"
19 },
20
21 schema: []
22 },
23
24 create(context) {
25
26 return {
27
28 ForInStatement(node) {
29 const body = node.body;
30
31 // empty statement
32 if (body.type === "EmptyStatement") {
33 return;
34 }
35
36 // if statement
37 if (body.type === "IfStatement") {
38 return;
39 }
40
41 // empty block
42 if (body.type === "BlockStatement" && body.body.length === 0) {
43 return;
44 }
45
46 // block with just if statement
47 if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
48 return;
49 }
50
51 // block that starts with if statement
52 if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
53 const i = body.body[0];
54
55 // ... whose consequent is a continue
56 if (i.consequent.type === "ContinueStatement") {
57 return;
58 }
59
60 // ... whose consequent is a block that contains only a continue
61 if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
62 return;
63 }
64 }
65
66 context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." });
67 }
68 };
69
70 }
71};