diff --git a/lib/util/ast.js b/lib/util/ast.js index 596ae9fdaf..747b448429 100644 --- a/lib/util/ast.js +++ b/lib/util/ast.js @@ -232,6 +232,15 @@ function isFunction(node) { return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; } +/** + * Checks if node is a function declaration or expression or arrow function. + * @param {ASTNode} node The node to check + * @return {Boolean} true if it's a function-like + */ +function isFunctionLike(node) { + return node.type === 'FunctionDeclaration' || isFunctionLikeExpression(node); +} + /** * Checks if the node is a class. * @param {ASTNode} node The node to check @@ -432,6 +441,7 @@ module.exports = { isClass, isFunction, isFunctionLikeExpression, + isFunctionLike, inConstructor, isNodeFirstInLine, unwrapTSAsExpression, diff --git a/tests/util/ast.js b/tests/util/ast.js index 607a90a99b..d5f9bbe718 100644 --- a/tests/util/ast.js +++ b/tests/util/ast.js @@ -7,6 +7,7 @@ const espree = require('espree'); const ast = require('../../lib/util/ast'); const traverseReturns = ast.traverseReturns; +const isFunctionLike = ast.isFunctionLike; const DEFAULT_CONFIG = { ecmaVersion: 6, @@ -101,4 +102,76 @@ describe('ast', () => { }); }); }); + + describe('isFunctionLike()', () => { + it('FunctionDeclaration should return true', () => { + const node1 = parseCode(` + function foo(bar) { + const asdf = () => 'zxcv'; + return asdf; + } + `); + assert.strictEqual(isFunctionLike(node1), true); + + const node2 = parseCode(` + function foo({bar}) { + const asdf = () => 'zxcv'; + console.log(bar); + return '5' + } + `); + assert.strictEqual(isFunctionLike(node2), true); + }); + + it('FunctionExpression should return true', () => { + const node1 = parseCode(` + const foo = function(bar) { + return () => 'zxcv'; + } + `).declarations[0].init; + assert.strictEqual(isFunctionLike(node1), true); + + const node2 = parseCode(` + const foo = function ({bar}) { + return '5'; + } + `).declarations[0].init; + assert.strictEqual(isFunctionLike(node2), true); + }); + + it('ArrowFunctionExpression should return true', () => { + const node1 = parseCode(` + (bar) => { + return () => 'zxcv'; + } + `).expression; + assert.strictEqual(isFunctionLike(node1), true); + + const node2 = parseCode(` + ({bar}) => '5'; + `).expression; + assert.strictEqual(isFunctionLike(node2), true); + + const node3 = parseCode(` + bar => '5'; + `).expression; + assert.strictEqual(isFunctionLike(node3), true); + }); + + it('Non-functions should return false', () => { + const node1 = parseCode(` + class bar { + a() { + return 'a'; + } + } + `); + assert.strictEqual(isFunctionLike(node1), false); + + const node2 = parseCode(` + const a = 5; + `); + assert.strictEqual(isFunctionLike(node2), false); + }); + }); });