Skip to content

Commit

Permalink
Fix: Unused recursive function expressions should be flagged (fixes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
sergei-startsev committed Oct 30, 2018
1 parent 9771442 commit 03e2981
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/rules/no-unused-vars.js
Expand Up @@ -223,6 +223,32 @@ module.exports = {
return false;
}

/**
* Gets a list of function definitions for a specified variable.
* @param {Variable} variable - eslint-scope variable object.
* @returns {ASTNode[]} Function nodes.
* @private
*/
function getFunctionDefinitions(variable) {
const functionDefinitions = [];

variable.defs.forEach(def => {
const { type, node } = def;

// FunctionDeclarations
if (type === "FunctionName") {
functionDefinitions.push(node);
}

// FunctionExpressions
if (type === "Variable" && node.init &&
(node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
functionDefinitions.push(node.init);
}
});
return functionDefinitions;
}

/**
* Checks the position of given nodes.
*
Expand Down Expand Up @@ -435,7 +461,7 @@ module.exports = {
* @private
*/
function isUsedVariable(variable) {
const functionNodes = variable.defs.filter(def => def.type === "FunctionName").map(def => def.node),
const functionNodes = getFunctionDefinitions(variable),
isFunctionDefinition = functionNodes.length > 0;
let rhsNode = null;

Expand Down
23 changes: 23 additions & 0 deletions tests/lib/rules/no-unused-vars.js
Expand Up @@ -717,6 +717,29 @@ ruleTester.run("no-unused-vars", rule, {
code: "(function(_a) {})();",
options: [{ args: "all", caughtErrorsIgnorePattern: "^_" }],
errors: [{ message: "'_a' is defined but never used." }]
},

// https://github.com/eslint/eslint/issues/10982
{
code: "var a = function () { a(); };",
errors: [{ message: "'a' is assigned a value but never used." }]
},
{
code: "var a = function(){ function foo() { a(); } };",
errors: [
{ message: "'a' is assigned a value but never used." },
{ message: "'foo' is defined but never used." }
]
},
{
code: "const a = () => { a(); };",
parserOptions: { ecmaVersion: 2015 },
errors: [{ message: "'a' is assigned a value but never used." }]
},
{
code: "const a = () => () => { a(); };",
parserOptions: { ecmaVersion: 2015 },
errors: [{ message: "'a' is assigned a value but never used." }]
}
]
});

0 comments on commit 03e2981

Please sign in to comment.