UNPKG

2.01 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag the use of redundant constructors in classes.
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
15 /**
16 * Checks whether the constructor body is a redundant super call.
17 * @param {Array} body - constructor body content.
18 * @param {Array} ctorParams - The params to check against super call.
19 * @returns {boolean} true if the construtor body is redundant
20 */
21 function isRedundantSuperCall(body, ctorParams) {
22 if (body.length !== 1 ||
23 body[0].type !== "ExpressionStatement" ||
24 body[0].expression.callee.type !== "Super") {
25 return false;
26 }
27
28
29 return body[0].expression.arguments.every(function(arg, index) {
30 return (arg.type === "Identifier" && arg.name === ctorParams[index].name) ||
31 (
32 arg.type === "SpreadElement" &&
33 ctorParams[index].type === "RestElement" &&
34 arg.argument.name === ctorParams[index].argument.name
35 );
36 });
37 }
38
39 /**
40 * Checks whether a node is a redundant construtor
41 * @param {ASTNode} node - node to check
42 * @returns {void}
43 */
44 function checkForConstructor(node) {
45 if (node.kind !== "constructor") {
46 return;
47 }
48
49 var body = node.value.body.body;
50
51 if (!node.parent.parent.superClass && body.length === 0 ||
52 node.parent.parent.superClass && isRedundantSuperCall(body, node.value.params)) {
53 context.report(node, "Useless constructor.");
54 }
55 }
56
57
58 return {
59 "MethodDefinition": checkForConstructor
60 };
61};
62
63module.exports.schema = [];