diff --git a/src/common/util.js b/src/common/util.js index 3b047427a..4baf93597 100644 --- a/src/common/util.js +++ b/src/common/util.js @@ -298,6 +298,10 @@ const equalityOperators = { "===": true, "!==": true }; +const additiveOperators = { + "+": true, + "-": true +}; const multiplicativeOperators = { "*": true, "/": true, @@ -311,6 +315,11 @@ const bitshiftOperators = { function shouldFlatten(parentOp, nodeOp) { if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { + // x + y % z --> (x + y) % z + if (nodeOp === "%" && !additiveOperators[parentOp]) { + return true; + } + return false; } diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js index 5e385d11a..c404d29f0 100644 --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -259,6 +259,10 @@ function needsParens(path, options) { return true; } + if (pp < np && no === "%") { + return !util.shouldFlatten(po, no); + } + // Add parenthesis when working with binary operators // It's not stricly needed but helps with code understanding if (util.isBitwiseOperator(po)) { diff --git a/tests/binary_math/__snapshots__/jsfmt.spec.js.snap b/tests/binary_math/__snapshots__/jsfmt.spec.js.snap index d6e4d5e3c..728ce3f1d 100644 --- a/tests/binary_math/__snapshots__/jsfmt.spec.js.snap +++ b/tests/binary_math/__snapshots__/jsfmt.spec.js.snap @@ -14,6 +14,11 @@ mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; 2 / 3 * 10 / 2 + 2; const rotateX = ((RANGE / rect.height) * refY - RANGE / 2) * getXMultiplication(rect.width); const rotateY = ((RANGE / rect.width) * refX - RANGE / 2) * getYMultiplication(rect.width); + +a % 10 - 5; +a * b % 10; +a % 10 > 5; +a % 10 == 0; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const result = (a + b) >>> 1; var sizeIndex = ((index - 1) >>> level) & MASK; @@ -32,4 +37,9 @@ const rotateX = const rotateY = ((RANGE / rect.width) * refX - RANGE / 2) * getYMultiplication(rect.width); +(a % 10) - 5; +(a * b) % 10; +a % 10 > 5; +a % 10 == 0; + `; diff --git a/tests/binary_math/parens.js b/tests/binary_math/parens.js index 73a897091..846cdff17 100644 --- a/tests/binary_math/parens.js +++ b/tests/binary_math/parens.js @@ -11,3 +11,8 @@ mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; 2 / 3 * 10 / 2 + 2; const rotateX = ((RANGE / rect.height) * refY - RANGE / 2) * getXMultiplication(rect.width); const rotateY = ((RANGE / rect.width) * refX - RANGE / 2) * getYMultiplication(rect.width); + +a % 10 - 5; +a * b % 10; +a % 10 > 5; +a % 10 == 0;