sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
3.98k stars 361 forks source link

Rule proposal: `no-unnecessary-splice` #2359

Open burtek opened 1 month ago

burtek commented 1 month ago

Description

Saw splice being used instead of push/pop/shift/unshift in some projects. AFAIK it brings no performance gain and is harder to read/understand than the latter ones.

Basically bans:

Fail

array.splice(start, 0)
array.splice(0, 1)
array.splice(array.length, 0, element)

Pass

array.shift()
array.push(element)

Proposed rule name

no-unnecessary-splice

Additional Info

Happy to work on this once accepted (already have a stub).

This would make #2165 not needed any more

fisker commented 1 month ago

Related https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2165

fisker commented 1 month ago

Fail

array.splice(index, 1, newValue);

Pass

array[index] = newValue;
array = array.with(index, newValue);
burtek commented 1 month ago

@fisker good one, but I'd prefer to have that configurable, as it depends on the targeted ECMA version if array.with is supported

EDIT: actually, this doesn't look like that good of a replacement. splice mutates the array and returns old values, same for push/pop/shift/unshift, but neither array[index] = newValue or array.with does it, so it changes the logic, especially since array can't be const for the array.with solution.

Will leave this one for the end

burtek commented 1 month ago

One thing to watch out for is whether splice's return value is used or not.

Another thing is for all calls like getArray().splice(4, 0) (no-op case), we cant just remove the whole thing, as we'd be removing call to getArray which might introduce bugs. A lot to consider for auto-fixer. Again, have some stub for this already, working on more

sindresorhus commented 1 month ago

Accepted

burtek commented 1 month ago

2361 is WIP, will try finishing it in the coming week.

q2p commented 4 days ago

Hello, I'm curious if there is any progress on this proposal?