Skip to content

Commit

Permalink
no-useless-spread: Remove unsafe fix (#1996)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored Nov 28, 2022
1 parent 4bbc469 commit 6756cbd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 14 deletions.
22 changes: 20 additions & 2 deletions rules/no-useless-spread.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const isOnSameLine = require('./utils/is-on-same-line.js');
const {
isParenthesized,
} = require('./utils/parentheses.js');
const {isNewExpression} = require('./ast/index.js');

const SPREAD_IN_LIST = 'spread-in-list';
const ITERABLE_TO_ARRAY = 'iterable-to-array';
Expand Down Expand Up @@ -279,11 +280,28 @@ const create = context => {
},
[uselessArrayCloneSelector](node) {
const arrayExpression = node.parent.parent;
return {
const problem = {
node: arrayExpression,
messageId: CLONE_ARRAY,
fix: fixer => unwrapSingleArraySpread(fixer, arrayExpression, sourceCode),
};

if (
// `[...new Array(1)]` -> `new Array(1)` is not safe to fix since there are holes
isNewExpression(node, {name: 'Array'})
// `[...foo.slice(1)]` -> `foo.slice(1)` is not safe to fix since `foo` can be a string
|| (
node.type === 'CallExpression'
&& node.callee.type === 'MemberExpression'
&& node.callee.property.type === 'Identifier'
&& node.callee.property.name === 'slice'
)
) {
return problem;
}

return Object.assign(problem, {
fix: fixer => unwrapSingleArraySpread(fixer, arrayExpression, sourceCode),
});
},
};
};
Expand Down
12 changes: 0 additions & 12 deletions test/snapshots/no-useless-spread.mjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1653,12 +1653,6 @@ Generated by [AVA](https://avajs.dev).
## Invalid #7
1 | [...foo.slice(1)]

> Output
`␊
1 | foo.slice(1)␊
`

> Error 1/1
`␊
Expand Down Expand Up @@ -1765,12 +1759,6 @@ Generated by [AVA](https://avajs.dev).
## Invalid #14
1 | [...new Array(3)]

> Output
`␊
1 | new Array(3)␊
`

> Error 1/1
`␊
Expand Down
Binary file modified test/snapshots/no-useless-spread.mjs.snap
Binary file not shown.

0 comments on commit 6756cbd

Please sign in to comment.