UNPKG

2.7 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to enforce a particular function style
3 * @author Nicholas C. Zakas
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11module.exports = {
12 meta: {
13 docs: {
14 description: "enforce the consistent use of either `function` declarations or expressions",
15 category: "Stylistic Issues",
16 recommended: false
17 },
18
19 schema: [
20 {
21 enum: ["declaration", "expression"]
22 },
23 {
24 type: "object",
25 properties: {
26 allowArrowFunctions: {
27 type: "boolean"
28 }
29 },
30 additionalProperties: false
31 }
32 ]
33 },
34
35 create(context) {
36
37 const style = context.options[0],
38 allowArrowFunctions = context.options[1] && context.options[1].allowArrowFunctions === true,
39 enforceDeclarations = (style === "declaration"),
40 stack = [];
41
42 const nodesToCheck = {
43 FunctionDeclaration(node) {
44 stack.push(false);
45
46 if (!enforceDeclarations && node.parent.type !== "ExportDefaultDeclaration") {
47 context.report({ node, message: "Expected a function expression." });
48 }
49 },
50 "FunctionDeclaration:exit"() {
51 stack.pop();
52 },
53
54 FunctionExpression(node) {
55 stack.push(false);
56
57 if (enforceDeclarations && node.parent.type === "VariableDeclarator") {
58 context.report({ node: node.parent, message: "Expected a function declaration." });
59 }
60 },
61 "FunctionExpression:exit"() {
62 stack.pop();
63 },
64
65 ThisExpression() {
66 if (stack.length > 0) {
67 stack[stack.length - 1] = true;
68 }
69 }
70 };
71
72 if (!allowArrowFunctions) {
73 nodesToCheck.ArrowFunctionExpression = function() {
74 stack.push(false);
75 };
76
77 nodesToCheck["ArrowFunctionExpression:exit"] = function(node) {
78 const hasThisExpr = stack.pop();
79
80 if (enforceDeclarations && !hasThisExpr && node.parent.type === "VariableDeclarator") {
81 context.report({ node: node.parent, message: "Expected a function declaration." });
82 }
83 };
84 }
85
86 return nodesToCheck;
87
88 }
89};