Skip to content

Commit

Permalink
feat: add support for arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
gajus committed Dec 19, 2021
1 parent 5bb7c22 commit ab3a17b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/rules/destructuringPropertyNewline.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,42 @@ export default {
const sourceCode = context.getSourceCode();

return {
ObjectPattern (node) {
ArrayPattern: (node) => {
if (allowSameLine && node.elements.length > 1) {
const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.elements[0]);
const lastTokenOfLastProperty = sourceCode.getLastToken(node.elements[node.properties.length - 1]);

if (firstTokenOfFirstProperty.loc.end.line === lastTokenOfLastProperty.loc.start.line) {
// All keys and values are on the same line
return;
}
}

for (let index = 1; index < node.elements.length; index++) {
const lastTokenOfPreviousProperty = sourceCode.getLastToken(node.elements[index - 1]);
const firstTokenOfCurrentProperty = sourceCode.getFirstToken(node.elements[index]);

if (lastTokenOfPreviousProperty.loc.end.line === firstTokenOfCurrentProperty.loc.start.line) {
context.report({
fix (fixer) {
const comma = sourceCode.getTokenBefore(firstTokenOfCurrentProperty);
const rangeAfterComma = [comma.range[1], firstTokenOfCurrentProperty.range[0]];

// Don't perform a fix if there are any comments between the comma and the next property.
if (sourceCode.text.slice(rangeAfterComma[0], rangeAfterComma[1]).trim()) {
return null;
}

return fixer.replaceTextRange(rangeAfterComma, '\n');
},
loc: firstTokenOfCurrentProperty.loc,
messageId,
node,
});
}
}
},
ObjectPattern: (node) => {
if (allowSameLine && node.properties.length > 1) {
const firstTokenOfFirstProperty = sourceCode.getFirstToken(node.properties[0]);
const lastTokenOfLastProperty = sourceCode.getLastToken(node.properties[node.properties.length - 1]);
Expand Down
7 changes: 7 additions & 0 deletions tests/rules/assertions/destructuringPropertyNewline.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ export default {
}],
output: 'const {a,\nb} = obj;',
},
{
code: 'const [a,b] = obj;',
errors: [{
messageId: 'propertiesOnNewline',
}],
output: 'const [a,\nb] = obj;',
},
{
code: 'const {a,b,c} = obj;',
errors: [
Expand Down

0 comments on commit ab3a17b

Please sign in to comment.