forked from sindresorhus/eslint-plugin-unicorn
/
no-array-reduce.js
94 lines (84 loc) · 2.25 KB
/
no-array-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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const {get} = require('lodash');
const {methodCallSelector} = require('./selectors/index.js');
const {arrayPrototypeMethodSelector, notFunctionSelector, matches} = require('./selectors/index.js');
const MESSAGE_ID = 'no-reduce';
const messages = {
[MESSAGE_ID]: '`Array#{{method}}()` is not allowed',
};
const prototypeSelector = method => [
methodCallSelector(method),
arrayPrototypeMethodSelector({
path: 'callee.object',
methods: ['reduce', 'reduceRight'],
}),
].join('');
const selector = matches([
// `array.{reduce,reduceRight}()`
[
methodCallSelector({methods: ['reduce', 'reduceRight'], minimumArguments: 1, maximumArguments: 2}),
notFunctionSelector('arguments.0'),
' > .callee > .property',
].join(''),
// `[].{reduce,reduceRight}.call()` and `Array.{reduce,reduceRight}.call()`
[
prototypeSelector('call'),
notFunctionSelector('arguments.1'),
' > .callee > .object > .property',
].join(''),
// `[].{reduce,reduceRight}.apply()` and `Array.{reduce,reduceRight}.apply()`
[
prototypeSelector('apply'),
' > .callee > .object > .property',
].join(''),
]);
const schema = [
{
type: 'object',
additionalProperties: false,
properties: {
allowSimpleOperations: {
type: 'boolean',
default: true,
},
},
},
];
const create = context => {
const {allowSimpleOperations} = {allowSimpleOperations: true, ...context.options[0]};
return {
[selector](node) {
const callback = get(node, 'parent.parent.arguments[0]', {});
const problem = {
node,
messageId: MESSAGE_ID,
data: {method: node.name},
};
if (!allowSimpleOperations) {
return problem;
}
if (callback.type === 'ArrowFunctionExpression' && callback.body.type === 'BinaryExpression') {
return;
}
if ((callback.type === 'ArrowFunctionExpression' || callback.type === 'FunctionExpression')
&& callback.body.type === 'BlockStatement'
&& callback.body.body.length === 1
&& callback.body.body[0].type === 'ReturnStatement'
&& callback.body.body[0].argument.type === 'BinaryExpression') {
return;
}
return problem;
},
};
};
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Disallow `Array#reduce()` and `Array#reduceRight()`.',
},
schema,
messages,
},
};