eslint-plugin-unicorn
Version:
More than 300 powerful ESLint rules
70 lines (60 loc) • 2.12 kB
JavaScript
import isNewExpressionWithParentheses from './is-new-expression-with-parentheses.js';
import {isDecimalIntegerNode} from './numeric.js';
import {getParenthesizedText, isParenthesized} from './parentheses/parentheses.js';
/**
@import {TSESTree as ESTree} from '@typescript-eslint/types';
@import * as ESLint from 'eslint';
*/
/**
Check if parentheses should be added to a `node` when it's used as an `object` of `MemberExpression`.
@param {ESTree.Node} node - The AST node to check.
@param {ESLint.Rule.RuleContext} context - The ESLint rule context object.
@returns {boolean}
*/
export default function shouldAddParenthesesToMemberExpressionObject(node, context) {
switch (node.type) {
// This is not a full list. Some other nodes like `FunctionDeclaration` don't need parentheses,
// but it's not possible to be in the place we are checking at this point.
// `FunctionExpression` is not in this list, `(function() {}).foo` needs parentheses.
case 'Identifier':
case 'MemberExpression':
case 'CallExpression':
case 'ChainExpression':
case 'TemplateLiteral':
case 'ThisExpression':
case 'Super':
case 'ArrayExpression':
case 'MetaProperty':
case 'ImportExpression':
case 'TaggedTemplateExpression':
case 'TSNonNullExpression': {
return false;
}
case 'NewExpression': {
return !isNewExpressionWithParentheses(node, context);
}
case 'Literal': {
/* node:coverage ignore next */
return Boolean(isDecimalIntegerNode(node));
}
default: {
return true;
}
}
}
/**
Get the text of `node` for use as the `object` of a `MemberExpression`, keeping its existing parentheses and adding parentheses when needed, for example `(a + b).foo` instead of `a + b.foo`.
@param {ESTree.Node} node - The AST node.
@param {ESLint.Rule.RuleContext} context - The ESLint rule context object.
@returns {string}
*/
export function getMemberExpressionObjectText(node, context) {
const text = getParenthesizedText(node, context);
if (
!isParenthesized(node, context)
&& shouldAddParenthesesToMemberExpressionObject(node, context)
) {
return `(${text})`;
}
return text;
}