forked from sindresorhus/eslint-plugin-unicorn
/
prefer-set-size.js
101 lines (84 loc) · 2.37 KB
/
prefer-set-size.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
'use strict';
const {findVariable} = require('eslint-utils');
const {memberExpressionSelector} = require('./selectors/index.js');
const {fixSpaceAroundKeyword} = require('./fix/index.js');
const MESSAGE_ID = 'prefer-set-size';
const messages = {
[MESSAGE_ID]: 'Prefer use `Set#size` instead of `Array#length`.',
};
const lengthAccessSelector = [
memberExpressionSelector('length'),
'[object.type="ArrayExpression"]',
'[object.elements.length=1]',
'[object.elements.0.type="SpreadElement"]',
].join('');
const isNewSet = node =>
node?.type === 'NewExpression'
&& node.callee.type === 'Identifier'
&& node.callee.name === 'Set';
function isSet(node, scope) {
if (isNewSet(node)) {
return true;
}
if (node.type !== 'Identifier') {
return false;
}
const variable = findVariable(scope, node);
if (!variable || variable.defs.length !== 1) {
return false;
}
const [definition] = variable.defs;
if (definition.type !== 'Variable' || definition.kind !== 'const') {
return false;
}
const declarator = definition.node;
return declarator.type === 'VariableDeclarator'
&& declarator.id.type === 'Identifier'
&& isNewSet(definition.node.init);
}
// `[...set].length` -> `set.size`
function fix(sourceCode, lengthAccessNodes) {
const {
object: arrayExpression,
property,
} = lengthAccessNodes;
const set = arrayExpression.elements[0].argument;
if (sourceCode.getCommentsInside(arrayExpression).length > sourceCode.getCommentsInside(set).length) {
return;
}
/** @param {import('eslint').Rule.RuleFixer} fixer */
return function * (fixer) {
yield fixer.replaceText(property, 'size');
yield fixer.replaceText(arrayExpression, sourceCode.getText(set));
yield * fixSpaceAroundKeyword(fixer, lengthAccessNodes, sourceCode);
};
}
/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
const sourceCode = context.getSourceCode();
return {
[lengthAccessSelector](node) {
const maybeSet = node.object.elements[0].argument;
if (!isSet(maybeSet, context.getScope())) {
return;
}
return {
node: node.property,
messageId: MESSAGE_ID,
fix: fix(sourceCode, node),
};
},
};
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer use `Set#size` instead of convert it to Array first.',
},
fixable: 'code',
messages,
},
};