UNPKG

2.75 kBJavaScriptView Raw
1/**
2 * require and specify a consistent function style for components
3 *
4 * Anonymous or named functions inside AngularJS components.
5 * The first parameter sets which type of function is required and can be 'named' or 'anonymous'.
6 * The second parameter is an optional list of angular object names.
7 *
8 * @linkDescription require and specify a consistent function style for components ('named' or 'anonymous')
9 * @styleguideReference {johnpapa} `y024` Named vs Anonymous Functions
10 * @version 0.1.0
11 * @category conventions
12 * @sinceAngularVersion 1.x
13 */
14'use strict';
15
16var utils = require('./utils/utils');
17
18module.exports = {
19 meta: {
20 schema: [{
21 enum: [
22 'named',
23 'anonymous'
24 ]
25 }, {
26 type: 'array',
27 items: {
28 type: 'string'
29 }
30 }]
31 },
32 create: function(context) {
33 var angularObjectList = ['animation', 'config', 'constant', 'controller', 'directive', 'factory', 'filter', 'provider', 'service', 'value', 'decorator'];
34 var configType = context.options[0] || 'anonymous';
35 var messageByConfigType = {
36 anonymous: 'Use anonymous functions instead of named function',
37 named: 'Use named functions instead of anonymous function'
38 };
39 var message = messageByConfigType[configType];
40
41 if (context.options[1]) {
42 angularObjectList = context.options[1];
43 }
44
45 function checkType(arg) {
46 return utils.isCallExpression(arg) ||
47 (configType === 'named' && (utils.isIdentifierType(arg) || utils.isNamedInlineFunction(arg))) ||
48 (configType === 'anonymous' && utils.isFunctionType(arg) && !utils.isNamedInlineFunction(arg));
49 }
50
51 return {
52
53 CallExpression: function(node) {
54 var callee = node.callee;
55 var angularObjectName = callee.property && callee.property.name;
56 var firstArgument = node.arguments[1];
57
58 if (utils.isAngularComponent(node) && callee.type === 'MemberExpression' && angularObjectList.indexOf(angularObjectName) >= 0) {
59 if (checkType(firstArgument)) {
60 return;
61 }
62
63 if (utils.isArrayType(firstArgument)) {
64 var last = firstArgument.elements[firstArgument.elements.length - 1];
65 if (checkType(last) || (!utils.isFunctionType(last) && !utils.isIdentifierType(last))) {
66 return;
67 }
68 }
69
70 context.report(node, message, {});
71 }
72 }
73 };
74 }
75};