sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-split-limit`

Open

#2,464 opened on Oct 3, 2024

View on GitHub
 (5 comments) (5 reactions) (0 assignees)JavaScript (5,022 stars) (468 forks)user submission
help wantednew rule

Description

Description

Whenever we use String.prototype.split with literals like so:

string.split('/')[0]
// or
string.split('/')[1]
// or
string.split('/')[2]

We benefit by limiting the search space, this allows split to exit early once it attains the number of splits and to not scan the whole string:

string.split('/', 1)[0]
// and
string.split('/', 2)[1]
// and
string.split('/', 3)[2]

// Once we get to the element we want, .split exits early (faster)

Fail

string.split('/')[0]
string.split('/').at(0)

Pass

string.split('/', 1)[0]
string.split('/', 1).at(0)
string.split('/').at(-1)
string.split('/').at(numberVar)
string.split('/')[numberVar]

Proposed rule name

specify-split-limit or prefer-split-limit

Additional Info

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#limit

Contributor guide