sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.31k stars 365 forks source link

Rule proposal: prefer-split-limit #2464

Open gurgunday opened 1 month ago

gurgunday commented 1 month ago

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

fregante commented 1 month ago
string.split('/').at(numberVar)

Could also be:

string.split('/', numberVar).at(numberVar)
gurgunday commented 1 month ago

Yeah

Just a small correction in case anyone starts implementing the rule -- since the second parameter is the length of the returned array instead of the number of splits to do:

string.split('/').at(numberVar)

// would be:

string.split('/', numberVar + 1).at(numberVar)
fregante commented 1 month ago

The rule could potentially also warn for that:


s.split('/', 1).at(2);
// Error: This will always be undefined