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

Fix(prefer-at): remove unsafe autofix for `.slice` with 1 argument

Open k-yle opened this issue 1 year ago • 0 comments

It's not safe to change array.slice(-n)[0] to array.at(-n). This code is not equivalent for arrays with only 1 item. It's only equivalent for .slice(-1)

Proof:

testCases = [ 'a', 'ab', 'abc', 'abcd' ];
testCases.map(array => ({
    original: array.slice(-2)[0],
    autofixed: array.at(-2),
}));

// output:
[ 
  {original: 'a', autofixed: undefined}, // 🔴 this is different
  {original: 'a', autofixed: 'a'},
  {original: 'b', autofixed: 'b'},
  {original: 'c', autofixed: 'c'},
]

k-yle avatar Oct 11 '24 08:10 k-yle