From f12def6b875d9dc9cd5c900dc8ec866eb0659940 Mon Sep 17 00:00:00 2001 From: Teddy Katz Date: Thu, 14 Sep 2017 20:58:09 -0400 Subject: [PATCH] Update: indent flatTernary option to handle `return` (fixes #9285) (#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. --- lib/rules/indent.js | 10 +++++----- tests/lib/rules/indent.js | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/lib/rules/indent.js b/lib/rules/indent.js index 07aa1e830a3..0f6468a7e15 100644 --- a/lib/rules/indent.js +++ b/lib/rules/indent.js @@ -950,12 +950,12 @@ 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")) { @@ -963,7 +963,7 @@ module.exports = { } node = node.parent; - return !node || node.range[0] === token.range[0]; + return !node || node.loc.start.line === token.loc.start.line; } const baseOffsetListeners = { @@ -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 === ":"); diff --git a/tests/lib/rules/indent.js b/tests/lib/rules/indent.js index 1339c16f642..006d7f1dd67 100644 --- a/tests/lib/rules/indent.js +++ b/tests/lib/rules/indent.js @@ -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 [