UNPKG

3.63 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to require braces in arrow function body.
3 * @author Alberto Rodríguez
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = {
12 meta: {
13 docs: {
14 description: "require braces around arrow function bodies",
15 category: "ECMAScript 6",
16 recommended: false
17 },
18
19 schema: {
20 anyOf: [
21 {
22 type: "array",
23 items: [
24 {
25 enum: ["always", "never"]
26 }
27 ],
28 minItems: 0,
29 maxItems: 1
30 },
31 {
32 type: "array",
33 items: [
34 {
35 enum: ["as-needed"]
36 },
37 {
38 type: "object",
39 properties: {
40 requireReturnForObjectLiteral: {type: "boolean"}
41 },
42 additionalProperties: false
43 }
44 ],
45 minItems: 0,
46 maxItems: 2
47 }
48 ]
49 }
50 },
51
52 create(context) {
53 const options = context.options;
54 const always = options[0] === "always";
55 const asNeeded = !options[0] || options[0] === "as-needed";
56 const never = options[0] === "never";
57 const requireReturnForObjectLiteral = options[1] && options[1].requireReturnForObjectLiteral;
58
59 /**
60 * Determines whether a arrow function body needs braces
61 * @param {ASTNode} node The arrow function node.
62 * @returns {void}
63 */
64 function validate(node) {
65 const arrowBody = node.body;
66
67 if (arrowBody.type === "BlockStatement") {
68 if (never) {
69 context.report({
70 node,
71 loc: arrowBody.loc.start,
72 message: "Unexpected block statement surrounding arrow body."
73 });
74 } else {
75 const blockBody = arrowBody.body;
76
77 if (blockBody.length !== 1) {
78 return;
79 }
80
81 if (asNeeded && requireReturnForObjectLiteral && blockBody[0].type === "ReturnStatement" &&
82 blockBody[0].argument.type === "ObjectExpression") {
83 return;
84 }
85
86 if (asNeeded && blockBody[0].type === "ReturnStatement") {
87 context.report({
88 node,
89 loc: arrowBody.loc.start,
90 message: "Unexpected block statement surrounding arrow body."
91 });
92 }
93 }
94 } else {
95 if (always || (asNeeded && requireReturnForObjectLiteral && arrowBody.type === "ObjectExpression")) {
96 context.report({
97 node,
98 loc: arrowBody.loc.start,
99 message: "Expected block statement surrounding arrow body."
100 });
101 }
102 }
103 }
104
105 return {
106 ArrowFunctionExpression: validate
107 };
108 }
109};