UNPKG

1.71 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to require braces in arrow function body.
3 * @author Alberto Rodríguez
4 * @copyright 2015 Alberto Rodríguez. All rights reserved.
5 * See LICENSE file in root directory for full license.
6 */
7"use strict";
8
9//------------------------------------------------------------------------------
10// Rule Definition
11//------------------------------------------------------------------------------
12
13module.exports = function(context) {
14 var always = context.options[0] === "always";
15 var asNeeded = !context.options[0] || context.options[0] === "as-needed";
16
17 /**
18 * Determines whether a arrow function body needs braces
19 * @param {ASTNode} node The arrow function node.
20 * @returns {void}
21 */
22 function validate(node) {
23 var arrowBody = node.body;
24 if (arrowBody.type === "BlockStatement") {
25 var blockBody = arrowBody.body;
26
27 if (blockBody.length !== 1) {
28 return;
29 }
30
31 if (asNeeded && blockBody[0].type === "ReturnStatement") {
32 context.report({
33 node: node,
34 loc: arrowBody.loc.start,
35 message: "Unexpected block statement surrounding arrow body."
36 });
37 }
38 } else {
39 if (always) {
40 context.report({
41 node: node,
42 loc: arrowBody.loc.start,
43 message: "Expected block statement surrounding arrow body."
44 });
45 }
46 }
47 }
48
49 return {
50 "ArrowFunctionExpression": validate
51 };
52};
53
54module.exports.schema = [
55 {
56 "enum": ["always", "as-needed"]
57 }
58];