2 * @fileoverview Enforce newlines between operands of ternary expressions
8 const astUtils
= require("./utils/ast-utils");
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
19 description
: "enforce newlines between operands of ternary expressions",
20 category
: "Stylistic Issues",
22 url
: "https://eslint.org/docs/rules/multiline-ternary"
27 enum: ["always", "always-multiline", "never"]
31 expectedTestCons
: "Expected newline between test and consequent of ternary expression.",
32 expectedConsAlt
: "Expected newline between consequent and alternate of ternary expression.",
33 unexpectedTestCons
: "Unexpected newline between test and consequent of ternary expression.",
34 unexpectedConsAlt
: "Unexpected newline between consequent and alternate of ternary expression."
39 const option
= context
.options
[0];
40 const multiline
= option
!== "never";
41 const allowSingleLine
= option
=== "always-multiline";
43 //--------------------------------------------------------------------------
45 //--------------------------------------------------------------------------
48 * Tests whether node is preceded by supplied tokens
49 * @param {ASTNode} node node to check
50 * @param {ASTNode} parentNode parent of node to report
51 * @param {boolean} expected whether newline was expected or not
55 function reportError(node
, parentNode
, expected
) {
58 messageId
: `${expected ? "expected" : "unexpected"}${node === parentNode.test ? "TestCons" : "ConsAlt"}`
62 //--------------------------------------------------------------------------
64 //--------------------------------------------------------------------------
67 ConditionalExpression(node
) {
68 const areTestAndConsequentOnSameLine
= astUtils
.isTokenOnSameLine(node
.test
, node
.consequent
);
69 const areConsequentAndAlternateOnSameLine
= astUtils
.isTokenOnSameLine(node
.consequent
, node
.alternate
);
72 if (!areTestAndConsequentOnSameLine
) {
73 reportError(node
.test
, node
, false);
76 if (!areConsequentAndAlternateOnSameLine
) {
77 reportError(node
.consequent
, node
, false);
80 if (allowSingleLine
&& node
.loc
.start
.line
=== node
.loc
.end
.line
) {
84 if (areTestAndConsequentOnSameLine
) {
85 reportError(node
.test
, node
, true);
88 if (areConsequentAndAlternateOnSameLine
) {
89 reportError(node
.consequent
, node
, true);