eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: `prefer-change-array-by-copy`
"Change Array by copy" proposal
Fail
array.reverse();
array.sort();
const array = [...foo];
array.splice(0, 1);
const array = [...foo];
array[1] = 'changed';
Pass
array = array.toReversed();
array = array.toSorted();
const array = foo.toSpliced(0, 1);
const array = foo.with(1, 'changed');
Good idea. This will have to wait until it's shipping in a browser/Node.js version. The naming of the methods are not final.
I don't know, if the intent is to replace the existing variable, I don't particularly see an advantage in using with*
For example:
list.splice(1, 3); // Drop unwanted items
but also
const removedItems = list.splice(1, 3); // Drop unwanted items and save them elsewhere
However I agree that this should be an error:
const newArray = old.reverse()
The proposal has updated, see https://github.com/tc39/proposal-change-array-by-copy/commit/752e576db3d55e9d1d80a97df1f1e54c26ffbd7f
withReversed->toReversedwithSorted->toSortedwithSpliced->toSplicedwithAt->with
One pattern that I've been using is to clone arrays in the function parameters and I hope it can be preserved. I think the same thing applies to array destructuring.
Before
function foo(originalBar) {
const bar = [...originalBar];
return bar;
}
After
function foo([...bar] /* Shallow bar clone*/) {
return bar;
}
This hit Stage 4 today, so we should see it start shipping soon more than likely 👀
Maybe we should split this into separate rules, to make rules easier to maintain.
prefer-array-to-reversedprefer-array-to-sortedprefer-array-to-splicedprefer-array-with
With the release of Firefox 115, these methods are now available in all major browsers!
85%+ support according to caniuse
Should also detect cases where Array.from is used to shallow-clone, e.g. when unicorn/prefer-spread is disabled:
Fail
const sorted = Array.from(arr).sort();
Pass
const sorted = arr.toSorted();
Bump. @sindresorhus this has been around for a few months in all browsers now and in Node 20, so any chance we could get this in now?
This is accepted. Pull requests are welcome :)