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", "never"]
|
24 | }
|
25 | ]
|
26 | },
|
27 |
|
28 | create(context) {
|
29 | const multiline = context.options[0] !== "never";
|
30 |
|
31 | //--------------------------------------------------------------------------
|
32 | // Helpers
|
33 | //--------------------------------------------------------------------------
|
34 |
|
35 | /**
|
36 | * Tests whether node is preceded by supplied tokens
|
37 | * @param {ASTNode} node - node to check
|
38 | * @param {ASTNode} parentNode - parent of node to report
|
39 | * @param {boolean} expected - whether newline was expected or not
|
40 | * @returns {void}
|
41 | * @private
|
42 | */
|
43 | function reportError(node, parentNode, expected) {
|
44 | context.report({
|
45 | node,
|
46 | message: "{{expected}} newline between {{typeOfError}} of ternary expression.",
|
47 | data: {
|
48 | expected: expected ? "Expected" : "Unexpected",
|
49 | typeOfError: node === parentNode.test ? "test and consequent" : "consequent and alternate"
|
50 | }
|
51 | });
|
52 | }
|
53 |
|
54 | //--------------------------------------------------------------------------
|
55 | // Public
|
56 | //--------------------------------------------------------------------------
|
57 |
|
58 | return {
|
59 | ConditionalExpression(node) {
|
60 | const areTestAndConsequentOnSameLine = astUtils.isTokenOnSameLine(node.test, node.consequent);
|
61 | const areConsequentAndAlternateOnSameLine = astUtils.isTokenOnSameLine(node.consequent, node.alternate);
|
62 |
|
63 | if (!multiline) {
|
64 | if (!areTestAndConsequentOnSameLine) {
|
65 | reportError(node.test, node, false);
|
66 | }
|
67 |
|
68 | if (!areConsequentAndAlternateOnSameLine) {
|
69 | reportError(node.consequent, node, false);
|
70 | }
|
71 | } else {
|
72 | if (areTestAndConsequentOnSameLine) {
|
73 | reportError(node.test, node, true);
|
74 | }
|
75 |
|
76 | if (areConsequentAndAlternateOnSameLine) {
|
77 | reportError(node.consequent, node, true);
|
78 | }
|
79 | }
|
80 | }
|
81 | };
|
82 | }
|
83 | };
|