diff --git a/src/printer.js b/src/printer.js index 2b2085f7..1472748f 100644 --- a/src/printer.js +++ b/src/printer.js @@ -2567,7 +2567,18 @@ function printBinaryishExpressions(path, parts, print, options, isNested) { parts.push(path.call(print, "left")); } - parts.push(" ", node.operator, line, path.call(print, "right")); + const right = concat([node.operator, line, path.call(print, "right")]); + + // If there's only a single binary expression: everything except && and ||, + // we want to create a group in order to avoid having a small right part + // like -1 be on its own line. + const parent = path.getParentNode(); + const shouldGroup = node.type === "BinaryExpression" && + parent.type !== "BinaryExpression" && + node.left.type !== "BinaryExpression" && + node.right.type !== "BinaryExpression"; + + parts.push(" ", shouldGroup ? group(right) : right); // The root comments are already printed, but we need to manually print // the other ones since we don't call the normal print on BinaryExpression, diff --git a/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap b/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap index fd646320..31d4ce31 100644 --- a/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap +++ b/tests/binary-expressions/__snapshots__/jsfmt.spec.js.snap @@ -1,3 +1,36 @@ +exports[`test short-right.js 1`] = ` +"this._cumulativeHeights && + Math.abs( + this._cachedItemHeight(this._firstVisibleIndex + i) - + this._provider.fastHeight(i + this._firstVisibleIndex), + ) > + 1 + +foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( + aaaaaaaaaaaaaaaaaaa +) + + a; + +const isPartOfPackageJSON = dependenciesArray.indexOf( + dependencyWithOutRelativePath.split(\'/\')[0], +) !== -1; +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +this._cumulativeHeights && + Math.abs( + this._cachedItemHeight(this._firstVisibleIndex + i) - + this._provider.fastHeight(i + this._firstVisibleIndex) + ) > 1; + +foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( + aaaaaaaaaaaaaaaaaaa +) + a; + +const isPartOfPackageJSON = dependenciesArray.indexOf( + dependencyWithOutRelativePath.split(\"/\")[0] +) !== -1; +" +`; + exports[`test test.js 1`] = ` "// It should always break the highest precedence operators first, and // break them all at the same time. diff --git a/tests/binary-expressions/short-right.js b/tests/binary-expressions/short-right.js new file mode 100644 index 00000000..7e82c2ad --- /dev/null +++ b/tests/binary-expressions/short-right.js @@ -0,0 +1,15 @@ +this._cumulativeHeights && + Math.abs( + this._cachedItemHeight(this._firstVisibleIndex + i) - + this._provider.fastHeight(i + this._firstVisibleIndex), + ) > + 1 + +foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( + aaaaaaaaaaaaaaaaaaa +) + + a; + +const isPartOfPackageJSON = dependenciesArray.indexOf( + dependencyWithOutRelativePath.split('/')[0], +) !== -1;