2 * @fileoverview Rule to disallow Math.pow in favor of the ** operator
3 * @author Milos Djermanovic
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
13 const { CALL, ReferenceTracker } = require("eslint-utils");
15 //------------------------------------------------------------------------------
17 //------------------------------------------------------------------------------
19 const PRECEDENCE_OF_EXPONENTIATION_EXPR = astUtils.getPrecedence({ type: "BinaryExpression", operator: "**" });
22 * Determines whether the given node needs parens if used as the base in an exponentiation binary expression.
23 * @param {ASTNode} base The node to check.
24 * @returns {boolean} `true` if the node needs to be parenthesised.
26 function doesBaseNeedParens(base) {
29 // '**' is right-associative, parens are needed when Math.pow(a ** b, c) is converted to (a ** b) ** c
30 astUtils.getPrecedence(base) <= PRECEDENCE_OF_EXPONENTIATION_EXPR ||
32 // An unary operator cannot be used immediately before an exponentiation expression
33 base.type === "UnaryExpression"
38 * Determines whether the given node needs parens if used as the exponent in an exponentiation binary expression.
39 * @param {ASTNode} exponent The node to check.
40 * @returns {boolean} `true` if the node needs to be parenthesised.
42 function doesExponentNeedParens(exponent) {
44 // '**' is right-associative, there is no need for parens when Math.pow(a, b ** c) is converted to a ** b ** c
45 return astUtils.getPrecedence(exponent) < PRECEDENCE_OF_EXPONENTIATION_EXPR;
49 * Determines whether an exponentiation binary expression at the place of the given node would need parens.
50 * @param {ASTNode} node A node that would be replaced by an exponentiation binary expression.
51 * @param {SourceCode} sourceCode A SourceCode object.
52 * @returns {boolean} `true` if the expression needs to be parenthesised.
54 function doesExponentiationExpressionNeedParens(node, sourceCode) {
55 const parent = node.parent;
58 parent.type === "ClassDeclaration" ||
60 parent.type.endsWith("Expression") &&
61 astUtils.getPrecedence(parent) >= PRECEDENCE_OF_EXPONENTIATION_EXPR &&
62 !(parent.type === "BinaryExpression" && parent.operator === "**" && parent.right === node) &&
63 !((parent.type === "CallExpression" || parent.type === "NewExpression") && parent.arguments.includes(node)) &&
64 !(parent.type === "MemberExpression" && parent.computed && parent.property === node) &&
65 !(parent.type === "ArrayExpression")
69 return needsParens && !astUtils.isParenthesised(sourceCode, node);
73 * Optionally parenthesizes given text.
74 * @param {string} text The text to parenthesize.
75 * @param {boolean} shouldParenthesize If `true`, the text will be parenthesised.
76 * @returns {string} parenthesised or unchanged text.
78 function parenthesizeIfShould(text, shouldParenthesize) {
79 return shouldParenthesize ? `(${text})` : text;
82 //------------------------------------------------------------------------------
84 //------------------------------------------------------------------------------
91 description: "disallow the use of `Math.pow` in favor of the `**` operator",
92 category: "Stylistic Issues",
94 url: "https://eslint.org/docs/rules/prefer-exponentiation-operator"
101 useExponentiation: "Use the '**' operator instead of 'Math.pow'."
106 const sourceCode = context.getSourceCode();
109 * Reports the given node.
110 * @param {ASTNode} node 'Math.pow()' node to report.
113 function report(node) {
116 messageId: "useExponentiation",
119 node.arguments.length !== 2 ||
120 node.arguments.some(arg => arg.type === "SpreadElement") ||
121 sourceCode.getCommentsInside(node).length > 0
126 const base = node.arguments[0],
127 exponent = node.arguments[1],
128 baseText = sourceCode.getText(base),
129 exponentText = sourceCode.getText(exponent),
130 shouldParenthesizeBase = doesBaseNeedParens(base),
131 shouldParenthesizeExponent = doesExponentNeedParens(exponent),
132 shouldParenthesizeAll = doesExponentiationExpressionNeedParens(node, sourceCode);
137 if (!shouldParenthesizeAll) {
138 if (!shouldParenthesizeBase) {
139 const firstReplacementToken = sourceCode.getFirstToken(base),
140 tokenBefore = sourceCode.getTokenBefore(node);
144 tokenBefore.range[1] === node.range[0] &&
145 !astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)
147 prefix = " "; // a+Math.pow(++b, c) -> a+ ++b**c
150 if (!shouldParenthesizeExponent) {
151 const lastReplacementToken = sourceCode.getLastToken(exponent),
152 tokenAfter = sourceCode.getTokenAfter(node);
156 node.range[1] === tokenAfter.range[0] &&
157 !astUtils.canTokensBeAdjacent(lastReplacementToken, tokenAfter)
159 suffix = " "; // Math.pow(a, b)in c -> a**b in c
164 const baseReplacement = parenthesizeIfShould(baseText, shouldParenthesizeBase),
165 exponentReplacement = parenthesizeIfShould(exponentText, shouldParenthesizeExponent),
166 replacement = parenthesizeIfShould(`${baseReplacement}**${exponentReplacement}`, shouldParenthesizeAll);
168 return fixer.replaceText(node, `${prefix}${replacement}${suffix}`);
175 const scope = context.getScope();
176 const tracker = new ReferenceTracker(scope);
179 pow: { [CALL]: true }
183 for (const { node } of tracker.iterateGlobalReferences(trackMap)) {