/
trailing-commas.js
73 lines (60 loc) · 2.12 KB
/
trailing-commas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import CoreRule from '../../core/rule.js';
/**
* TrailingCommas
*
* Print trailing commas wherever possible in multi-line comma-separated syntactic structures. (A single-line array, for example, never gets trailing commas.)
*
* @see https://prettier.io/docs/en/options.html#trailing-commas
*/
export default class RuleTrailingCommas extends CoreRule
{
/**
* @var string
*/
get default() {
return 'es5';
}
/**
* @var string
*/
get property() {
return 'trailingCommas';
}
/**
* Mandatory entry function to create a decision
*
* @return boolean
*/
identify() {
let output = this.default;
let hasTrailingCommas = false;
let hasNonTrailingCommas = false;
// Determine if any have quotes
this.arrayBrackets.forEach(block => {
block = `{${block}}`;
// Checks for objects the end with a comma
hasTrailingCommas = [...block.matchAll(/,\s*[})]/gms)].length > 0 || hasTrailingCommas;
// Checks for lines that end without commas but also exist across
// multiple lines (as to avoid single line arrays)
hasNonTrailingCommas = [...block.matchAll(/[a-zA-Z'"\]\}]\s*\n\s*[})]/gms)].length > 0 || hasNonTrailingCommas;
});
// Determine if any have quotes
this.objectBlocks.forEach(block => {
block = `{${block}}`;
// Checks for objects the end with a comma
hasTrailingCommas = [...block.matchAll(/,\s*[})]/gms)].length > 0 || hasTrailingCommas;
// Checks for lines that end without commas but also exist across
// multiple lines (as to avoid single line arrays)
hasNonTrailingCommas = [...block.matchAll(/[a-zA-Z'"\]\}]\s*\n\s*[})]/gms)].length > 0 || hasNonTrailingCommas;
});
// Set consistent if we don't mix quotes
if (hasTrailingCommas && !hasNonTrailingCommas) {
output = 'all';
}
// No trailing commas
else if (!hasTrailingCommas) {
output = 'none';
}
return output;
}
}