all files / eslint-plugin-angular/rules/ function-type.js

100% Statements 23/23
100% Branches 26/26
100% Functions 3/3
100% Lines 23/23
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 62 63 64 65 66 67 68 69 70 71                              132× 132× 132×       132×   132×     175×       132×     167× 167× 167×   167× 123× 36×     87× 52× 52× 28×       59×                                
/**
 * require and specify a consistent function style for components
 *
 * Anonymous or named functions inside AngularJS components.
 * The first parameter sets which type of function is required and can be 'named' or 'anonymous'.
 * The second parameter is an optional list of angular object names.
 *
 * @linkDescription require and specify a consistent function style for components ('named' or 'anonymous')
 * @styleguideReference {johnpapa} `y024` Named vs Anonymous Functions
 * @version 0.1.0
 * @category conventions
 */
'use strict';
 
var utils = require('./utils/utils');
 
module.exports = function(context) {
    var angularObjectList = ['animation', 'config', 'constant', 'controller', 'directive', 'factory', 'filter', 'provider', 'service', 'value', 'decorator'];
    var configType = context.options[0] || 'anonymous';
    var messageByConfigType = {
        anonymous: 'Use anonymous functions instead of named function',
        named: 'Use named functions instead of anonymous function'
    };
    var message = messageByConfigType[configType];
 
    if (context.options[1]) {
        angularObjectList = context.options[1];
    }
 
    function checkType(arg) {
        return (configType === 'named' && (utils.isIdentifierType(arg) || utils.isNamedInlineFunction(arg))) ||
            (configType === 'anonymous' && utils.isFunctionType(arg) && !utils.isNamedInlineFunction(arg));
    }
 
    return {
 
        CallExpression: function(node) {
            var callee = node.callee;
            var angularObjectName = callee.property && callee.property.name;
            var firstArgument = node.arguments[1];
 
            if (utils.isAngularComponent(node) && callee.type === 'MemberExpression' && angularObjectList.indexOf(angularObjectName) >= 0) {
                if (checkType(firstArgument)) {
                    return;
                }
 
                if (utils.isArrayType(firstArgument)) {
                    var last = firstArgument.elements[firstArgument.elements.length - 1];
                    if (checkType(last) || (!utils.isFunctionType(last) && !utils.isIdentifierType(last))) {
                        return;
                    }
                }
 
                context.report(node, message, {});
            }
        }
    };
};
 
module.exports.schema = [{
    enum: [
        'named',
        'anonymous'
    ]
}, {
    type: 'array',
    items: {
        type: 'string'
    }
}];