1 | /**
|
2 | * @fileoverview Enforce newlines between operands of ternary expressions
|
3 | * @author Kai Cataldo
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | const astUtils = require("../ast-utils");
|
9 |
|
10 | //------------------------------------------------------------------------------
|
11 | // Rule Definition
|
12 | //------------------------------------------------------------------------------
|
13 |
|
14 | module.exports = {
|
15 | meta: {
|
16 | docs: {
|
17 | description: "enforce newlines between operands of ternary expressions",
|
18 | category: "Stylistic Issues",
|
19 | recommended: false
|
20 | },
|
21 | schema: [
|
22 | {
|
23 | enum: ["always", "always-multiline", "never"]
|
24 | }
|
25 | ]
|
26 | },
|
27 |
|
28 | create(context) {
|
29 | const option = context.options[0];
|
30 | const multiline = option !== "never";
|
31 | const allowSingleLine = option === "always-multiline";
|
32 |
|
33 | //--------------------------------------------------------------------------
|
34 | // Helpers
|
35 | //--------------------------------------------------------------------------
|
36 |
|
37 | /**
|
38 | * Tests whether node is preceded by supplied tokens
|
39 | * @param {ASTNode} node - node to check
|
40 | * @param {ASTNode} parentNode - parent of node to report
|
41 | * @param {boolean} expected - whether newline was expected or not
|
42 | * @returns {void}
|
43 | * @private
|
44 | */
|
45 | function reportError(node, parentNode, expected) {
|
46 | context.report({
|
47 | node,
|
48 | message: "{{expected}} newline between {{typeOfError}} of ternary expression.",
|
49 | data: {
|
50 | expected: expected ? "Expected" : "Unexpected",
|
51 | typeOfError: node === parentNode.test ? "test and consequent" : "consequent and alternate"
|
52 | }
|
53 | });
|
54 | }
|
55 |
|
56 | //--------------------------------------------------------------------------
|
57 | // Public
|
58 | //--------------------------------------------------------------------------
|
59 |
|
60 | return {
|
61 | ConditionalExpression(node) {
|
62 | const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(node.test, node.consequent);
|
63 | const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(node.consequent, node.alternate);
|
64 |
|
65 | if (!multiline) {
|
66 | if (!areTestAndConsequentOnSameLine) {
|
67 | reportError(node.test, node, false);
|
68 | }
|
69 |
|
70 | if (!areConsequentAndAlternateOnSameLine) {
|
71 | reportError(node.consequent, node, false);
|
72 | }
|
73 | } else {
|
74 | if (allowSingleLine && node.loc.start.line === node.loc.end.line) {
|
75 | return;
|
76 | }
|
77 |
|
78 | if (areTestAndConsequentOnSameLine) {
|
79 | reportError(node.test, node, true);
|
80 | }
|
81 |
|
82 | if (areConsequentAndAlternateOnSameLine) {
|
83 | reportError(node.consequent, node, true);
|
84 | }
|
85 | }
|
86 | }
|
87 | };
|
88 | }
|
89 | };
|