sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-split-limit`

Chiusa

#2464 aperta il 3 ott 2024

 (5 commenti) (5 reazioni) (0 assegnatari)JavaScript (468 fork)user submission
help wantednew rule

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 1g 16h) (399 PR mergiate in 30 g)

Descrizione

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

Guida contributor