]> git.proxmox.com Git - pve-eslint.git/blame - eslint/lib/rules/guard-for-in.js
change from CLIEngine to ESLint
[pve-eslint.git] / eslint / lib / rules / guard-for-in.js
CommitLineData
eb39fafa
DC
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 type: "suggestion",
15
16 docs: {
17 description: "require `for-in` loops to include an `if` statement",
eb39fafa
DC
18 recommended: false,
19 url: "https://eslint.org/docs/rules/guard-for-in"
20 },
21
22 schema: [],
23 messages: {
24 wrap: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype."
25 }
26 },
27
28 create(context) {
29
30 return {
31
32 ForInStatement(node) {
33 const body = node.body;
34
35 // empty statement
36 if (body.type === "EmptyStatement") {
37 return;
38 }
39
40 // if statement
41 if (body.type === "IfStatement") {
42 return;
43 }
44
45 // empty block
46 if (body.type === "BlockStatement" && body.body.length === 0) {
47 return;
48 }
49
50 // block with just if statement
51 if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
52 return;
53 }
54
55 // block that starts with if statement
56 if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
57 const i = body.body[0];
58
59 // ... whose consequent is a continue
60 if (i.consequent.type === "ContinueStatement") {
61 return;
62 }
63
64 // ... whose consequent is a block that contains only a continue
65 if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
66 return;
67 }
68 }
69
70 context.report({ node, messageId: "wrap" });
71 }
72 };
73
74 }
75};