forked from sindresorhus/eslint-plugin-unicorn
/
no-unreadable-array-destructuring.js
82 lines (69 loc) · 2.15 KB
/
no-unreadable-array-destructuring.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
'use strict';
const {isParenthesized} = require('eslint-utils');
const shouldAddParenthesesToMemberExpressionObject = require('./utils/should-add-parentheses-to-member-expression-object.js');
const {fixSpaceAroundKeyword} = require('./fix/index.js');
const MESSAGE_ID = 'no-unreadable-array-destructuring';
const messages = {
[MESSAGE_ID]: 'Array destructuring may not contain consecutive ignored values.',
};
const isCommaFollowedWithComma = (element, index, array) =>
element === null && array[index + 1] === null;
const create = context => {
const sourceCode = context.getSourceCode();
return {
'ArrayPattern[elements.length>=3]'(node) {
const {elements, parent} = node;
if (!elements.some((element, index, elements) => isCommaFollowedWithComma(element, index, elements))) {
return;
}
const problem = {
node,
messageId: MESSAGE_ID,
};
const nonNullElements = elements.filter(node => node !== null);
if (
parent.type === 'VariableDeclarator'
&& parent.id === node
&& parent.init !== null
&& nonNullElements.length === 1
) {
const [element] = nonNullElements;
if (element.type !== 'AssignmentPattern') {
problem.fix = function * (fixer) {
const index = elements.indexOf(element);
const isSlice = element.type === 'RestElement';
const variable = isSlice ? element.argument : element;
yield fixer.replaceText(node, sourceCode.getText(variable));
const code = isSlice ? `.slice(${index})` : `[${index}]`;
const array = parent.init;
if (
!isParenthesized(array, sourceCode)
&& shouldAddParenthesesToMemberExpressionObject(array, sourceCode)
) {
yield fixer.insertTextBefore(array, '(');
yield fixer.insertTextAfter(parent, `)${code}`);
} else {
yield fixer.insertTextAfter(parent, code);
}
yield * fixSpaceAroundKeyword(fixer, node, sourceCode);
};
}
}
return problem;
},
};
};
/**
* @type {import('eslint').Rule.RuleModule}
*/
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Disallow unreadable array destructuring.',
},
fixable: 'code',
messages,
},
};