1 | 'use strict';
|
2 | const methodSelector = require('./utils/method-selector');
|
3 | const getDocumentationUrl = require('./utils/get-documentation-url');
|
4 | const {notFunctionSelector} = require('./utils/not-function');
|
5 |
|
6 | const MESSAGE_ID_REDUCE = 'reduce';
|
7 | const MESSAGE_ID_REDUCE_RIGHT = 'reduceRight';
|
8 |
|
9 | const prototypeSelector = method => [
|
10 | methodSelector({name: method}),
|
11 | '[callee.object.type="MemberExpression"]',
|
12 | '[callee.object.computed=false]',
|
13 | `:matches(${
|
14 | ['reduce', 'reduceRight'].map(method => `[callee.object.property.name="${method}"]`).join(', ')
|
15 | })`,
|
16 | '[callee.object.property.type="Identifier"]',
|
17 | `:matches(${
|
18 | [
|
19 | // `[].reduce`
|
20 | [
|
21 | 'type="ArrayExpression"',
|
22 | 'elements.length=0'
|
23 | ],
|
24 | // `Array.prototype.reduce`
|
25 | [
|
26 | 'type="MemberExpression"',
|
27 | 'computed=false',
|
28 | 'property.type="Identifier"',
|
29 | 'property.name="prototype"',
|
30 | 'object.type="Identifier"',
|
31 | 'object.name="Array"'
|
32 | ]
|
33 | ].map(
|
34 | selectors => selectors
|
35 | .map(selector => `[callee.object.object.${selector}]`)
|
36 | .join('')
|
37 | ).join(', ')
|
38 | })`
|
39 | ].join('');
|
40 |
|
41 | const PROTOTYPE_CALL_SELECTOR = [
|
42 | prototypeSelector('call'),
|
43 | notFunctionSelector('arguments.1')
|
44 | ].join('');
|
45 |
|
46 | const PROTOTYPE_APPLY_SELECTOR = prototypeSelector('apply');
|
47 |
|
48 | const METHOD_SELECTOR = [
|
49 | methodSelector({names: ['reduce', 'reduceRight'], min: 1, max: 2}),
|
50 | notFunctionSelector('arguments.0')
|
51 | ].join('');
|
52 |
|
53 | const create = context => {
|
54 | return {
|
55 | [METHOD_SELECTOR](node) {
|
56 |
|
57 | context.report({node: node.callee.property, messageId: node.callee.property.name});
|
58 | },
|
59 | [PROTOTYPE_CALL_SELECTOR](node) {
|
60 |
|
61 | context.report({node: node.callee.object.property, messageId: node.callee.object.property.name});
|
62 | },
|
63 | [PROTOTYPE_APPLY_SELECTOR](node) {
|
64 |
|
65 | context.report({node: node.callee.object.property, messageId: node.callee.object.property.name});
|
66 | }
|
67 | };
|
68 | };
|
69 |
|
70 | module.exports = {
|
71 | create,
|
72 | meta: {
|
73 | type: 'suggestion',
|
74 | docs: {
|
75 | url: getDocumentationUrl(__filename)
|
76 | },
|
77 | messages: {
|
78 | [MESSAGE_ID_REDUCE]: '`Array#reduce()` is not allowed',
|
79 | [MESSAGE_ID_REDUCE_RIGHT]: '`Array#reduceRight()` is not allowed'
|
80 | }
|
81 | }
|
82 | };
|