123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189 |
- "use strict";
- function isSingleSuperCall(body) {
- return (
- body.length === 1 &&
- body[0].type === "ExpressionStatement" &&
- body[0].expression.type === "CallExpression" &&
- body[0].expression.callee.type === "Super"
- );
- }
- function isSimple(node) {
- return node.type === "Identifier" || node.type === "RestElement";
- }
- function isSpreadArguments(superArgs) {
- return (
- superArgs.length === 1 &&
- superArgs[0].type === "SpreadElement" &&
- superArgs[0].argument.type === "Identifier" &&
- superArgs[0].argument.name === "arguments"
- );
- }
- function isValidIdentifierPair(ctorParam, superArg) {
- return (
- ctorParam.type === "Identifier" &&
- superArg.type === "Identifier" &&
- ctorParam.name === superArg.name
- );
- }
- function isValidRestSpreadPair(ctorParam, superArg) {
- return (
- ctorParam.type === "RestElement" &&
- superArg.type === "SpreadElement" &&
- isValidIdentifierPair(ctorParam.argument, superArg.argument)
- );
- }
- function isValidPair(ctorParam, superArg) {
- return (
- isValidIdentifierPair(ctorParam, superArg) ||
- isValidRestSpreadPair(ctorParam, superArg)
- );
- }
- function isPassingThrough(ctorParams, superArgs) {
- if (ctorParams.length !== superArgs.length) {
- return false;
- }
- for (let i = 0; i < ctorParams.length; ++i) {
- if (!isValidPair(ctorParams[i], superArgs[i])) {
- return false;
- }
- }
- return true;
- }
- function isRedundantSuperCall(body, ctorParams) {
- return (
- isSingleSuperCall(body) &&
- ctorParams.every(isSimple) &&
- (
- isSpreadArguments(body[0].expression.arguments) ||
- isPassingThrough(ctorParams, body[0].expression.arguments)
- )
- );
- }
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "Disallow unnecessary constructors",
- recommended: false,
- url: "https://eslint.org/docs/latest/rules/no-useless-constructor"
- },
- schema: [],
- messages: {
- noUselessConstructor: "Useless constructor."
- }
- },
- create(context) {
-
- function checkForConstructor(node) {
- if (node.kind !== "constructor") {
- return;
- }
-
- if (!node.value.body) {
- return;
- }
- const body = node.value.body.body;
- const ctorParams = node.value.params;
- const superClass = node.parent.parent.superClass;
- if (superClass ? isRedundantSuperCall(body, ctorParams) : (body.length === 0)) {
- context.report({
- node,
- messageId: "noUselessConstructor"
- });
- }
- }
- return {
- MethodDefinition: checkForConstructor
- };
- }
- };
|