Skip to content

Commit 6756cbd

Browse files
authored
no-useless-spread: Remove unsafe fix (#1996)
1 parent 4bbc469 commit 6756cbd

File tree

3 files changed

+20
-14
lines changed

3 files changed

+20
-14
lines changed

rules/no-useless-spread.js

+20-2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const isOnSameLine = require('./utils/is-on-same-line.js');
1515
const {
1616
isParenthesized,
1717
} = require('./utils/parentheses.js');
18+
const {isNewExpression} = require('./ast/index.js');
1819

1920
const SPREAD_IN_LIST = 'spread-in-list';
2021
const ITERABLE_TO_ARRAY = 'iterable-to-array';
@@ -279,11 +280,28 @@ const create = context => {
279280
},
280281
[uselessArrayCloneSelector](node) {
281282
const arrayExpression = node.parent.parent;
282-
return {
283+
const problem = {
283284
node: arrayExpression,
284285
messageId: CLONE_ARRAY,
285-
fix: fixer => unwrapSingleArraySpread(fixer, arrayExpression, sourceCode),
286286
};
287+
288+
if (
289+
// `[...new Array(1)]` -> `new Array(1)` is not safe to fix since there are holes
290+
isNewExpression(node, {name: 'Array'})
291+
// `[...foo.slice(1)]` -> `foo.slice(1)` is not safe to fix since `foo` can be a string
292+
|| (
293+
node.type === 'CallExpression'
294+
&& node.callee.type === 'MemberExpression'
295+
&& node.callee.property.type === 'Identifier'
296+
&& node.callee.property.name === 'slice'
297+
)
298+
) {
299+
return problem;
300+
}
301+
302+
return Object.assign(problem, {
303+
fix: fixer => unwrapSingleArraySpread(fixer, arrayExpression, sourceCode),
304+
});
287305
},
288306
};
289307
};

test/snapshots/no-useless-spread.mjs.md

-12
Original file line numberDiff line numberDiff line change
@@ -1653,12 +1653,6 @@ Generated by [AVA](https://avajs.dev).
16531653
## Invalid #7
16541654
1 | [...foo.slice(1)]
16551655

1656-
> Output
1657-
1658-
`␊
1659-
1 | foo.slice(1)␊
1660-
`
1661-
16621656
> Error 1/1
16631657
16641658
`␊
@@ -1765,12 +1759,6 @@ Generated by [AVA](https://avajs.dev).
17651759
## Invalid #14
17661760
1 | [...new Array(3)]
17671761

1768-
> Output
1769-
1770-
`␊
1771-
1 | new Array(3)␊
1772-
`
1773-
17741762
> Error 1/1
17751763
17761764
`␊
-7 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)