Skip to content

Commit

Permalink
prefer-exponentiation-operator: Fix operator precedence bugs (#305)
Browse files Browse the repository at this point in the history
  • Loading branch information
MrHen authored and sindresorhus committed May 31, 2019
1 parent 0f8d5b4 commit dc90c1e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 8 deletions.
31 changes: 24 additions & 7 deletions rules/prefer-exponentiation-operator.js
Expand Up @@ -12,17 +12,34 @@ const isMathPow = node => {
);
};

const parseArgument = (context, arg) => {
if (arg.type === 'Identifier') {
return arg.name;
}
const parseArgument = (source, arg) => {
const text = source.getText(arg);

return context.getSourceCode().getText(arg);
switch (arg.type) {
case 'Identifier':
return arg.name;
case 'Literal':
return text;
case 'CallExpression':
return text;
case 'UnaryExpression':
return text;
default:
// Handle cases like Math.pow(2, 2-1);
return `(${text})`;
}
};

const fix = (context, node, fixer) => {
const base = parseArgument(context, node.arguments[0]);
const exponent = parseArgument(context, node.arguments[1]);
const source = context.getSourceCode();
const comments = source.getCommentsInside(node);

if (comments && comments.length > 0) {
return;
}

const base = parseArgument(source, node.arguments[0]);
const exponent = parseArgument(source, node.arguments[1]);

const replacement = `${base} ** ${exponent}`;

Expand Down
32 changes: 31 additions & 1 deletion test/prefer-exponentiation-operator.js
Expand Up @@ -24,7 +24,7 @@ ruleTester.run('prefer-exponentiation-operator', rule, {
{
code: 'const x = Math.pow(-2, (2 - 4) +0 -0.2);',
errors: [{message}],
output: 'const x = -2 ** (2 - 4) +0 -0.2;'
output: 'const x = -2 ** ((2 - 4) +0 -0.2);'
},
{
code: 'const x = Math.pow(Math.pow(2, 4), 8);',
Expand All @@ -48,6 +48,36 @@ ruleTester.run('prefer-exponentiation-operator', rule, {
code: 'const x = Math.pow(foo(), bar());',
errors: [{message}],
output: 'const x = foo() ** bar();'
},
{
code: 'const x = Math.pow(-2, 2 - 4);',
errors: [{message}],
output: 'const x = -2 ** (2 - 4);'
},
{
code: 'const x = Math.pow(4 - 2, 2 - 4);',
errors: [{message}],
output: 'const x = (4 - 2) ** (2 - 4);'
},
{
code: 'const x = Math.pow(\n2,\n2);',
errors: [{message}],
output: 'const x = 2 ** 2;'
},
{
code: 'const x = Math.pow(\n2,2 +\n2);',
errors: [{message}],
output: 'const x = 2 ** (2 +\n2);'
},
{
code: 'const x = Math.pow(\n2, // foo\n2);',
errors: [{message}],
output: 'const x = Math.pow(\n2, // foo\n2);'
},
{
code: 'const x = Math.pow(// foo\n2, 2);',
errors: [{message}],
output: 'const x = Math.pow(// foo\n2, 2);'
}
]
});

0 comments on commit dc90c1e

Please sign in to comment.