/
explicit-length-check.js
117 lines (108 loc) · 2.29 KB
/
explicit-length-check.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import {outdent} from 'outdent';
import {test} from './utils/test';
const nonZeroCases = [
'foo.length',
'!!foo.length',
'foo.length !== 0',
'foo.length != 0',
'foo.length > 0',
'foo.length >= 1',
'0 !== foo.length',
'0 != foo.length',
'0 < foo.length',
'1 <= foo.length'
];
const zeroCases = [
'!foo.length',
'foo.length === 0',
'foo.length == 0',
'foo.length < 1',
'0 === foo.length',
'0 == foo.length',
'1 > foo.length'
];
test({
valid: [
// Not `.length`
'if (foo.notLength) {}',
'if (length) {}',
'if (foo[length]) {}',
'if (foo["length"]) {}',
// Not in `IfStatement` or `ConditionalExpression`
'foo.length',
'foo.length === 0',
'foo.length !== 0',
'foo.length > 0',
// Checking 'non-zero'
'if (foo.length > 0) {}',
{
code: 'if (foo.length > 0) {}',
options: [{'non-zero': 'greater-than'}]
},
{
code: 'if (foo.length !== 0) {}',
options: [{'non-zero': 'not-equal'}]
},
{
code: 'if (foo.length >= 1) {}',
options: [{'non-zero': 'greater-than-or-equal'}]
},
// Checking 'non-zero'
'if (foo.length === 0) {}',
// `ConditionalExpression`
'const bar = foo.length === 0 ? 1 : 2',
// `WhileStatement`
outdent`
while (foo.length > 0) {
foo.pop();
}
`,
// `DoWhileStatement`
outdent`
do {
foo.pop();
} while (foo.length > 0);
`,
// `ForStatement`
'for (; foo.length > 0; foo.pop());',
'if (foo.length !== 1) {}',
'if (foo.length > 1) {}',
'if (foo.length < 2) {}'
],
invalid: []
});
test.visualize([
outdent`
if (
!!!(
${zeroCases.filter(code => code !== 'foo.length === 0').join(' &&\n\t\t')}
) ||
!(
${nonZeroCases.filter(code => code !== 'foo.length > 0').join(' ||\n\t\t')}
)
) {}
`,
{
code: outdent`
if (
${nonZeroCases.filter(code => code !== 'foo.length !== 0').join(' ||\n\t')}
) {}
`,
options: [{'non-zero': 'not-equal'}]
},
{
code: outdent`
const foo = (
${nonZeroCases.filter(code => code !== 'foo.length >= 1').join(' &&\n\t')}
) ? 1 : 2;
`,
options: [{'non-zero': 'greater-than-or-equal'}]
},
'if (foo.bar && foo.bar.length) {}',
'if (foo.length || foo.bar()) {}',
'if (!!(!!foo.length)) {}',
'if (!(foo.length === 0)) {}',
'while (foo.length >= 1) {}',
'do {} while (foo.length);',
'for (let i = 0; (bar && !foo.length); i ++) {}'
]);