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";
42 const sourceCode
= context
.getSourceCode();
44 //--------------------------------------------------------------------------
46 //--------------------------------------------------------------------------
49 ConditionalExpression(node
) {
50 const questionToken
= sourceCode
.getTokenAfter(node
.test
, astUtils
.isNotClosingParenToken
);
51 const colonToken
= sourceCode
.getTokenAfter(node
.consequent
, astUtils
.isNotClosingParenToken
);
53 const firstTokenOfTest
= sourceCode
.getFirstToken(node
);
54 const lastTokenOfTest
= sourceCode
.getTokenBefore(questionToken
);
55 const firstTokenOfConsequent
= sourceCode
.getTokenAfter(questionToken
);
56 const lastTokenOfConsequent
= sourceCode
.getTokenBefore(colonToken
);
57 const firstTokenOfAlternate
= sourceCode
.getTokenAfter(colonToken
);
59 const areTestAndConsequentOnSameLine
= astUtils
.isTokenOnSameLine(lastTokenOfTest
, firstTokenOfConsequent
);
60 const areConsequentAndAlternateOnSameLine
= astUtils
.isTokenOnSameLine(lastTokenOfConsequent
, firstTokenOfAlternate
);
63 if (!areTestAndConsequentOnSameLine
) {
67 start
: firstTokenOfTest
.loc
.start
,
68 end
: lastTokenOfTest
.loc
.end
70 messageId
: "unexpectedTestCons"
74 if (!areConsequentAndAlternateOnSameLine
) {
76 node
: node
.consequent
,
78 start
: firstTokenOfConsequent
.loc
.start
,
79 end
: lastTokenOfConsequent
.loc
.end
81 messageId
: "unexpectedConsAlt"
85 if (allowSingleLine
&& node
.loc
.start
.line
=== node
.loc
.end
.line
) {
89 if (areTestAndConsequentOnSameLine
) {
93 start
: firstTokenOfTest
.loc
.start
,
94 end
: lastTokenOfTest
.loc
.end
96 messageId
: "expectedTestCons"
100 if (areConsequentAndAlternateOnSameLine
) {
102 node
: node
.consequent
,
104 start
: firstTokenOfConsequent
.loc
.start
,
105 end
: lastTokenOfConsequent
.loc
.end
107 messageId
: "expectedConsAlt"