/
no-reduce.js
78 lines (72 loc) · 1.96 KB
/
no-reduce.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
'use strict';
const methodSelector = require('./utils/method-selector');
const getDocumentationUrl = require('./utils/get-documentation-url');
const MESSAGE_ID_REDUCE = 'reduce';
const MESSAGE_ID_REDUCE_RIGHT = 'reduceRight';
const ignoredFirstArgumentSelector = `:not(${
[
'[arguments.0.type="Literal"]',
'[arguments.0.type="Identifier"][arguments.0.name="undefined"]'
].join(',')
})`;
const PROTOTYPE_SELECTOR = [
methodSelector({names: ['call', 'apply']}),
ignoredFirstArgumentSelector,
'[callee.object.type="MemberExpression"]',
'[callee.object.computed=false]',
`:matches(${
['reduce', 'reduceRight'].map(method => `[callee.object.property.name="${method}"]`).join(', ')
})`,
'[callee.object.property.type="Identifier"]',
`:matches(${
[
// `[].reduce`
[
'type="ArrayExpression"',
'elements.length=0'
],
// `Array.prototype.reduce`
[
'type="MemberExpression"',
'computed=false',
'property.type="Identifier"',
'property.name="prototype"',
'object.type="Identifier"',
'object.name="Array"'
]
].map(
selectors => selectors
.map(selector => `[callee.object.object.${selector}]`)
.join('')
).join(', ')
})`
].join('');
const METHOD_SELECTOR = [
methodSelector({names: ['reduce', 'reduceRight'], min: 1, max: 2}),
ignoredFirstArgumentSelector
].join('');
const create = context => {
return {
[METHOD_SELECTOR](node) {
// For arr.reduce()
context.report({node: node.callee.property, messageId: node.callee.property.name});
},
[PROTOTYPE_SELECTOR](node) {
// For cases [].reduce.call() and Array.prototype.reduce.call()
context.report({node: node.callee.object.property, messageId: node.callee.object.property.name});
}
};
};
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
url: getDocumentationUrl(__filename)
},
messages: {
[MESSAGE_ID_REDUCE]: '`Array#reduce()` is not allowed',
[MESSAGE_ID_REDUCE_RIGHT]: '`Array#reduceRight()` is not allowed'
}
}
};