Skip to content

Commit

Permalink
Update: indent flatTernary option to handle return (fixes #9285) (#…
Browse files Browse the repository at this point in the history
…9296)

This updates the `flatTernaryExpression` option of `indent` to check whether a ternary expression is on the same *line* as a statement, rather than checking if the expression itself starts the statement.
  • Loading branch information
not-an-aardvark committed Sep 15, 2017
1 parent e220687 commit f12def6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
10 changes: 5 additions & 5 deletions lib/rules/indent.js
Expand Up @@ -950,20 +950,20 @@ module.exports = {
}

/**
* Check whether the given token is the first token of a statement.
* Check whether the given token is on the first line of a statement.
* @param {Token} token The token to check.
* @param {ASTNode} leafNode The expression node that the token belongs directly.
* @returns {boolean} `true` if the token is the first token of a statement.
* @returns {boolean} `true` if the token is on the first line of a statement.
*/
function isFirstTokenOfStatement(token, leafNode) {
function isOnFirstLineOfStatement(token, leafNode) {
let node = leafNode;

while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
node = node.parent;
}
node = node.parent;

return !node || node.range[0] === token.range[0];
return !node || node.loc.start.line === token.loc.start.line;
}

const baseOffsetListeners = {
Expand Down Expand Up @@ -1076,7 +1076,7 @@ module.exports = {
// /*else*/ qiz ;
if (!options.flatTernaryExpressions ||
!astUtils.isTokenOnSameLine(node.test, node.consequent) ||
isFirstTokenOfStatement(firstToken, node)
isOnFirstLineOfStatement(firstToken, node)
) {
const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
Expand Down
25 changes: 25 additions & 0 deletions tests/lib/rules/indent.js
Expand Up @@ -3591,6 +3591,31 @@ ruleTester.run("indent", rule, {
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
function foo() {
return foo ? bar :
baz
}
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
throw foo ? bar :
baz
`,
options: [4, { flatTernaryExpressions: true }]
},
{
code: unIndent`
foo(
bar
) ? baz :
qux
`,
options: [4, { flatTernaryExpressions: true }]
},
unIndent`
foo
[
Expand Down

0 comments on commit f12def6

Please sign in to comment.