Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update: Added generators option to func-names (fixes #9511) #10697

Merged
43 changes: 21 additions & 22 deletions lib/rules/func-names.js
Expand Up @@ -65,14 +65,22 @@ module.exports = {
},

create(context) {
const never = context.options[0] === "never";
const asNeeded = context.options[0] === "as-needed";
let requireNamedGenerators = !never;
let asNeededGenerators = asNeeded;

if (context.options[1] && Object.prototype.hasOwnProperty.call(context.options[1], "generators")) {
requireNamedGenerators = context.options[1].generators !== "never";
asNeededGenerators = context.options[1].generators === "as-needed";

/**
* Returns the config option for the given node.
* @param {ASTNode} node - A node to get the config for.
* @returns {string} The config option.
*/
function getConfigForNode(node) {
if (
node.generator &&
context.options.length > 1 &&
context.options[1].generators
) {
return context.options[1].generators;
}

return context.options[0] || "always";
}

/**
Expand Down Expand Up @@ -147,24 +155,15 @@ module.exports = {
}

const hasName = Boolean(node.id && node.id.name);
const config = getConfigForNode(node);

if (node.generator) {
const failsAsNeededRequirement = asNeededGenerators ? !hasInferredName(node) : !isObjectOrClassMethod(node);

if (requireNamedGenerators && !hasName && failsAsNeededRequirement) {
reportUnexpectedUnnamedFunction(node);
} else if (!requireNamedGenerators && hasName) {
if (config === "never") {
if (hasName) {
reportUnexpectedNamedFunction(node);
}
} else {
if (never) {
if (hasName) {
reportUnexpectedNamedFunction(node);
}
} else {
if (!hasName && (asNeeded ? !hasInferredName(node) : !isObjectOrClassMethod(node))) {
reportUnexpectedUnnamedFunction(node);
}
if (!hasName && (config === "as-needed" ? !hasInferredName(node) : !isObjectOrClassMethod(node))) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be simplified to something like:

} else if (config === "as-needed") {
    if (!hasName && !hasInferredName(node)) {
        reportUnexpectedUnnamedFunction(node);
    }
} else {
    if (!isObjectOrClassMethod(node)) {
        reportUnexpectedUnnamedFunction(node);
    }
}

In my opinion, the expression !hasName && (config === "as-needed" ? !hasInferredName(node) : !isObjectOrClassMethod(node)) is fairly difficult to read and understand (most of this complexity was already there before this change).

reportUnexpectedUnnamedFunction(node);
}
}
}
Expand Down