πPutout plugin adds ability to remove useless spread
npm install @putout/plugin-spread[NPMIMGURL]: https://img.shields.io/npm/v/@putout/plugin-spread.svg?style=flat&longCache=true
[NPMURL]: https://npmjs.org/package/@putout/plugin-spread "npm"
> Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.
>
> (c) MDN
πPutout plugin adds ability to transform spread syntax.
```
npm i @putout/plugin-spread
- β
convert-apply-to-spread;
- β
convert-convert-object-assign-to-merge-spread;
- β
simplify-nested;
- β
remove-useless-array;
- β
remove-useless-object;
`json`
{
"rules": {
"spread/convert-apply-to-spread": "on",
"spread/convert-object-assign-to-merge-spread": "on",
"spread/remove-useless-array": "on",
"spread/remove-useless-object": "on",
"spread/simplify-nested": "on"
}
}
> The Object.assign() method copies all enumerable own properties from one or more source objects to a target object and returns the modified target object.
>
> Spread syntax (...) allows an object expression to be expanded in places where zero or more key-value pairs are expected.
>
> (c) MDN
Convert Object.assign() to merge spread since it shorter but does (mostly) the same.
`js`
function merge(a) {
return Object.assign({}, a, {
hello: 'world',
});
}
`js`
function merge(a) {
return {
...a,
hello: 'world',
};
}
Linter | Rule | Fix
--------|-------|------------|
π Putout | spread/convert-object-assign-to-merge-spread | β
β£ ESLint | prefer-object-spread | β
The thing is [...b] can be used for:
- copying an array;
- converting different value type like string to an array.
So better to be more concrete and use slice for copying and Array()/Array.from() for converting to decrease cognitive load.spread
Also sometimes there is no need on any of this operations, and we can drop .
`js
for (const a of [...b]) {}
const places = [...getPlaces()];
`
`js
for (const a of b) {}
const places = getPlaces();
// Array constructor creates sparse array
[...Array(5)].map(Number);
`
`js`
const a = {
...fn(),
};
`js`
const a = fn();
Checkout in πPutout Editor.
`js`
[
...[
...a,
...b,
],
...x,
];
`js`
[
...a,
...b,
...x,
];
> Spread syntax (...) allows an array expression to be expanded in places where zero or more arguments are expected.
>
> (c) MDN
`js`
console.apply(null, arguments);
`js``
console.log(...arguments);
MIT