eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: `prefer-change-array-by-copy`

Open fisker opened this issue 4 years ago • 13 comments

"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');

fisker avatar Sep 08 '21 02:09 fisker

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.

sindresorhus avatar Sep 08 '21 02:09 sindresorhus

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()

fregante avatar Sep 19 '21 08:09 fregante

The proposal has updated, see https://github.com/tc39/proposal-change-array-by-copy/commit/752e576db3d55e9d1d80a97df1f1e54c26ffbd7f

  • withReversed -> toReversed
  • withSorted -> toSorted
  • withSpliced -> toSpliced
  • withAt -> with

fisker avatar Dec 16 '21 04:12 fisker

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;
}

fregante avatar Mar 31 '22 14:03 fregante

This hit Stage 4 today, so we should see it start shipping soon more than likely 👀

Cherry avatar Jan 31 '23 00:01 Cherry

Maybe we should split this into separate rules, to make rules easier to maintain.

  • prefer-array-to-reversed
  • prefer-array-to-sorted
  • prefer-array-to-spliced
  • prefer-array-with

fisker avatar Jan 31 '23 00:01 fisker

With the release of Firefox 115, these methods are now available in all major browsers!

joealden avatar Jul 05 '23 17:07 joealden

85%+ support according to caniuse

klimashkin avatar Oct 12 '23 18:10 klimashkin

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();

silverwind avatar Jan 31 '24 16:01 silverwind

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?

markcarroll avatar Mar 27 '24 21:03 markcarroll

This is accepted. Pull requests are welcome :)

sindresorhus avatar Apr 03 '24 10:04 sindresorhus