-
-
Notifications
You must be signed in to change notification settings - Fork 354
/
prefer-array-some.js
106 lines (101 loc) · 2.47 KB
/
prefer-array-some.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
import {outdent} from 'outdent';
import {test} from './utils/test';
const MESSAGE_ID_ERROR = 'error';
const MESSAGE_ID_SUGGESTION = 'suggestion';
const invalidCase = ({code, suggestionOutput}) => ({
code,
output: code,
errors: [
{
messageId: MESSAGE_ID_ERROR,
suggestions: [
{
messageId: MESSAGE_ID_SUGGESTION,
output: suggestionOutput
}
]
}
]
});
test({
valid: [
// Not `boolean`
'const bar = foo.find(fn)',
'const bar = foo.find(fn) || baz',
// Not matched `CallExpression`
...[
// Not `CallExpression`
'new foo.find(fn)',
// Not `MemberExpression`
'find(fn)',
// `callee.property` is not a `Identifier`
'foo["find"](fn)',
'foo["fi" + "nd"](fn)',
'foo[`find`](fn)',
// Computed
'foo[find](fn)',
// Not `.find`
'foo.notFind(fn)',
// More or less argument(s)
'foo.find()',
'foo.find(fn, thisArgument, extraArgument)',
'foo.find(...argumentsArray)'
].map(code => `if (${code}) {}`)
],
invalid: [
...[
'const bar = !foo.find(fn)',
'const bar = Boolean(foo.find(fn))',
'if (foo.find(fn)) {}',
'const bar = foo.find(fn) ? 1 : 2',
'while (foo.find(fn)) foo.shift();',
'do {foo.shift();} while (foo.find(fn));',
'for (; foo.find(fn); ) foo.shift();',
'const bar = foo.find(fn) || baz'
].map(code => invalidCase({
code,
suggestionOutput: code.replace('find', 'some')
})),
// Comments
invalidCase({
code: 'console.log(foo /* comment 1 */ . /* comment 2 */ find /* comment 3 */ (fn) ? a : b)',
suggestionOutput: 'console.log(foo /* comment 1 */ . /* comment 2 */ some /* comment 3 */ (fn) ? a : b)'
}),
// This should not be reported, but `jQuery.find()` is always `truly`,
// It should not use as a boolean
invalidCase({
code: 'if (jQuery.find(".outer > div")) {}',
suggestionOutput: 'if (jQuery.some(".outer > div")) {}'
}),
// Actual messages
{
code: 'if (foo.find(fn)) {}',
output: 'if (foo.find(fn)) {}',
errors: [
{
message: 'Prefer `.some(…)` over `.find(…)`.',
suggestions: [
{
desc: 'Replace `.find(…)` with `.some(…)`.',
output: 'if (foo.some(fn)) {}'
}
]
}
]
}
]
});
test.visualize([
'if (array.find(element => element === "🦄")) {}',
'const foo = array.find(element => element === "🦄") ? bar : baz;',
outdent`
if (
array
.find(element => Array.isArray(element))
// ^^^^ This should NOT report
.find(x => x === 0)
// ^^^^ This should report
) {
}
`
]);