sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.27k stars 367 forks source link

Rule proposal: avoid loops to create `URLSearchParams` #2269

Open fregante opened 9 months ago

fregante commented 9 months ago

Description

It might be a bit niche, but not everyone knows that you can convert an object to a URLSearchParams without a for loop.

Fail

const tokenParams = new URLSearchParams();
for (const [param, value] of Object.entries(tokenBody)) {
  tokenParams.set(param, value);
}
new URLSearchParams(Object.entries(tokenBody))

Pass

new URLSearchParams(tokenBody)
// This piece of code is adding entries to an existing `URLSearchParam`
for (const [param, value] of Object.entries(tokenBody)) {
  tokenParams.set(param, value);
}

Additional Info

No response

silverwind commented 8 months ago

Do you even need the Object.entries? You haven't told what tokenBody is.


> new URLSearchParams(Object.entries({a: 1}))
URLSearchParams { 'a' => '1' }
> new URLSearchParams({a: 1})
URLSearchParams { 'a' => '1' }
fregante commented 8 months ago

Judging by MDN, that's seems to be accepted. I think the problem used to be typescript, but that works now too

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

silverwind commented 8 months ago

I guess this rule could apply to more than just URLSearchParams, basically anything that accepts a iterable in its constructor. Set is such an example, FormData is not. I'd call it prefer-iterable-in-constructor.

fregante commented 8 months ago

Objects are not iterable

silverwind commented 8 months ago

Right, so URLSearchParams is special in that it accepts objects, but the basic idea is the same in all cases, avoid a loop when a constructor can do the looping itself.

sindresorhus commented 6 months ago

Accepted. prefer-iterable-in-constructor