-
-
Notifications
You must be signed in to change notification settings - Fork 367
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Rule proposal: prefer-negative-index
for things like foo.slice
#415
Comments
It's good to have this rule to prevent this accident happen. Can't remember any other method use negative index except |
I added a few examples of where this is supported. Surprisingly, |
Good idea! |
test on chrome includes 'foobar'.includes('b', -5) // true
'foobar'.split('').includes('b', -5) // true
'foobar'.includes('b', -2) // true ???
'foobar'.split('').includes('b', -2) // false indexOf 'foobar'.indexOf('b', -5) // 3
'foobar'.split('').indexOf('b', -5) // 3
'foobar'.indexOf('b', -2) // 3 ???
'foobar'.split('').indexOf('b', -2) // -1 lastIndexOf 'foobar'.lastIndexOf('b', -5) // -1
'foobar'.split('').lastIndexOf('b', -5) // -1
'foobar'.lastIndexOf('b', -2) // -1 ???
'foobar'.split('').lastIndexOf('b', -2) // 3 and there is no |
If nobody is working on it, I'm going to do it |
I've done basic implementation. Need discussion
foo[1].slice(0, foo["1"].length - 1)
foo.bar.slice(0, foo['bar'].length - 1)
foo.slice(0, foo.length - 1 - 1)
Array.prototype.slice.call(foo, 0, foo.length - 1)
Array.prototype.slice.apply(foo, [0, foo.length - 1])
Array.prototype.slice.bind(foo)(0, foo.length - 1)
Array.prototype.slice.bind(foo, 0)(foo.length - 1)
Array.prototype.slice.bind(foo, 0, foo.length - 1)()
|
I think we should flag any usage of
|
Can't agree to this, we suppose to make // get half array
foo.slice(0, Math.floor(foo.length / 2)) |
Ah, yeah, I didn't think of that case. Then I'd just limit it to looking for a single Even more test cases:
To answer one of your other questions:
This gets weird because the math is bad but giving |
I just found simple remove foo.slice(0, foo.length - n)
foo.slice(0, foo.length - 0)
foo.slice(0, foo.length - (-1))
|
new proposal, only fix foo.length - POSITIVE_LITERAL_VALUE
foo.length - POSITIVE_LITERAL_VALUE - POSITIVE_LITERAL_VALUE and I think
will be too annoying |
See https://github.com/sindresorhus/eslint-plugin-unicorn/pull/409/files#diff-1e364de46e721b05ccf3d616d4248ebdR37
Functions that support negative indexing should use that feature instead of calculating from
length
.Fail
Pass
Functions
The text was updated successfully, but these errors were encountered: