summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/arrow-parens.js
blob: 78ce045017106f8a0fc789c68e2eb8ee3bcc6eca (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
/**
 * @fileoverview Rule to require parens in arrow function arguments.
 * @author Jxck
 */
"use strict";

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

module.exports = {
    meta: {
        docs: {
            description: "require parentheses around arrow function arguments",
            category: "ECMAScript 6",
            recommended: false
        },

        schema: [
            {
                enum: ["always", "as-needed"]
            }
        ]
    },

    create: function(context) {
        var message = "Expected parentheses around arrow function argument.";
        var asNeededMessage = "Unexpected parentheses around single function argument";
        var asNeeded = context.options[0] === "as-needed";

        /**
         * Determines whether a arrow function argument end with `)`
         * @param {ASTNode} node The arrow function node.
         * @returns {void}
         */
        function parens(node) {
            var token = context.getFirstToken(node);

            // as-needed: x => x
            if (asNeeded && node.params.length === 1 && node.params[0].type === "Identifier") {
                if (token.type === "Punctuator" && token.value === "(") {
                    context.report(node, asNeededMessage);
                }
                return;
            }

            if (token.type === "Identifier") {
                var after = context.getTokenAfter(token);

                // (x) => x
                if (after.value !== ")") {
                    context.report(node, message);
                }
            }
        }

        return {
            ArrowFunctionExpression: parens
        };
    }
};