Put short elements at right of single binary expression on same line (#605)

I've been trying to come up with a heuristic to stop putting small elements on a new line and I just realized that all the cases I found out only involved a single binary expression. If there's only a single operation, we can just put them on the same line (if it fits) and it's not going to look weird.

We do the same thing for MemberExpression where we only break if there are more than one ".".

Fixes #583
Fixes #503
master
Christopher Chedeau 2017-02-09 07:44:03 -08:00 committed by James Long
parent cda7650e27
commit 4a00bc33a5
3 changed files with 60 additions and 1 deletions

View File

@ -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,

View File

@ -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.

View File

@ -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;