]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/newline-per-chained-call.md
first commit
[pve-eslint.git] / eslint / docs / rules / newline-per-chained-call.md
1 # require a newline after each call in a method chain (newline-per-chained-call)
2
3 Chained method calls on a single line without line breaks are harder to read, so some developers place a newline character after each method call in the chain to make it more readable and easy to maintain.
4
5 Let's look at the following perfectly valid (but single line) code.
6
7 ```js
8 d3.select("body").selectAll("p").data([4, 8, 15, 16, 23, 42 ]).enter().append("p").text(function(d) { return "I'm number " + d + "!"; });
9 ```
10
11 However, with appropriate new lines, it becomes easy to read and understand. Look at the same code written below with line breaks after each call.
12
13 ```js
14 d3
15 .select("body")
16 .selectAll("p")
17 .data([
18 4,
19 8,
20 15,
21 16,
22 23,
23 42
24 ])
25 .enter()
26 .append("p")
27 .text(function (d) {
28 return "I'm number " + d + "!";
29 });
30 ```
31
32 Another argument in favor of this style is that it improves the clarity of diffs when something in the method chain is changed:
33
34 Less clear:
35
36 ```diff
37 -d3.select("body").selectAll("p").style("color", "white");
38 +d3.select("body").selectAll("p").style("color", "blue");
39 ```
40
41 More clear:
42
43 ```diff
44 d3
45 .select("body")
46 .selectAll("p")
47 - .style("color", "white");
48 + .style("color", "blue");
49 ```
50
51 ## Rule Details
52
53 This rule requires a newline after each call in a method chain or deep member access. Computed property accesses such as `instance[something]` are excluded.
54
55 ## Options
56
57 This rule has an object option:
58
59 * `"ignoreChainWithDepth"` (default: `2`) allows chains up to a specified depth.
60
61 ### ignoreChainWithDepth
62
63 Examples of **incorrect** code for this rule with the default `{ "ignoreChainWithDepth": 2 }` option:
64
65 ```js
66 /*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]*/
67
68 _.chain({}).map(foo).filter(bar).value();
69
70 // Or
71 _.chain({}).map(foo).filter(bar);
72
73 // Or
74 _
75 .chain({}).map(foo)
76 .filter(bar);
77
78 // Or
79 obj.method().method2().method3();
80 ```
81
82 Examples of **correct** code for this rule with the default `{ "ignoreChainWithDepth": 2 }` option:
83
84 ```js
85 /*eslint newline-per-chained-call: ["error", { "ignoreChainWithDepth": 2 }]*/
86
87 _
88 .chain({})
89 .map(foo)
90 .filter(bar)
91 .value();
92
93 // Or
94 _
95 .chain({})
96 .map(foo)
97 .filter(bar);
98
99 // Or
100 _.chain({})
101 .map(foo)
102 .filter(bar);
103
104 // Or
105 obj
106 .prop
107 .method().prop;
108
109 // Or
110 obj
111 .prop.method()
112 .method2()
113 .method3().prop;
114 ```
115
116 ## When Not To Use It
117
118 If you have conflicting rules or when you are fine with chained calls on one line, you can safely turn this rule off.