Skip to content

Commit

Permalink
[Refactor] add AST util isFunctionLike()
Browse files Browse the repository at this point in the history
  • Loading branch information
nix6839 authored and ljharb committed Mar 19, 2022
1 parent ef733fd commit 5554bd4
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/util/ast.js
Expand Up @@ -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
Expand Down Expand Up @@ -432,6 +441,7 @@ module.exports = {
isClass,
isFunction,
isFunctionLikeExpression,
isFunctionLike,
inConstructor,
isNodeFirstInLine,
unwrapTSAsExpression,
Expand Down
73 changes: 73 additions & 0 deletions tests/util/ast.js
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
});
});
});

0 comments on commit 5554bd4

Please sign in to comment.