eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule proposal: avoid loops to create `URLSearchParams`

Open fregante opened this issue 1 year ago • 6 comments

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

fregante avatar Feb 05 '24 10:02 fregante

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' }

silverwind avatar Feb 18 '24 01:02 silverwind

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

fregante avatar Feb 18 '24 01:02 fregante

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.

silverwind avatar Feb 19 '24 19:02 silverwind

Objects are not iterable

fregante avatar Feb 19 '24 20:02 fregante

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.

silverwind avatar Feb 19 '24 21:02 silverwind

Accepted. prefer-iterable-in-constructor

sindresorhus avatar May 07 '24 20:05 sindresorhus