summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/lib/rules/guard-for-in.js
blob: 6e8452a4844a6e740406c0ac4f2f4acfd152093c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
 * @fileoverview Rule to flag for-in loops without if statements inside
 * @author Nicholas C. Zakas
 */

"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "require `for-in` loops to include an `if` statement",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/guard-for-in"
        },

        schema: []
    },

    create(context) {

        return {

            ForInStatement(node) {
                const body = node.body;

                // empty statement
                if (body.type === "EmptyStatement") {
                    return;
                }

                // if statement
                if (body.type === "IfStatement") {
                    return;
                }

                // empty block
                if (body.type === "BlockStatement" && body.body.length === 0) {
                    return;
                }

                // block with just if statement
                if (body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "IfStatement") {
                    return;
                }

                // block that starts with if statement
                if (body.type === "BlockStatement" && body.body.length >= 1 && body.body[0].type === "IfStatement") {
                    const i = body.body[0];

                    // ... whose consequent is a continue
                    if (i.consequent.type === "ContinueStatement") {
                        return;
                    }

                    // ... whose consequent is a block that contains only a continue
                    if (i.consequent.type === "BlockStatement" && i.consequent.body.length === 1 && i.consequent.body[0].type === "ContinueStatement") {
                        return;
                    }
                }

                context.report({ node, message: "The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype." });
            }
        };

    }
};