eslint-plugin-sonarjs
Version:
39 lines (38 loc) • 1.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getImmediatelyInvokedFunction = getImmediatelyInvokedFunction;
exports.getImmediatelyConstructedFunction = getImmediatelyConstructedFunction;
const helpers_js_1 = require("./helpers.js");
/**
* Return a function literal that runs as a call target or template tag.
*
* `(function () {})()` and `(0, () => {})()` return their function.
* `(function* () {})()` and `(function () {}).call()` do not.
* The `.call` method can be replaced, so calling it might not run the function body.
*/
function getImmediatelyInvokedFunction(expression) {
const value = getFinalValue(expression);
return (value.type === 'FunctionExpression' || value.type === 'ArrowFunctionExpression') &&
!value.generator
? value
: undefined;
}
/**
* Return a synchronous constructor function literal.
*
* `new (function () {})()` returns its function. An async function and an arrow do not.
*/
function getImmediatelyConstructedFunction(expression) {
const value = getFinalValue(expression);
return value.type === 'FunctionExpression' && !value.async && !value.generator
? value
: undefined;
}
function getFinalValue(expression) {
const value = (0, helpers_js_1.unwrapTypeScriptValue)(expression);
if (value.type !== 'SequenceExpression') {
return value;
}
const lastExpression = value.expressions.at(-1);
return lastExpression ? getFinalValue(lastExpression) : value;
}