eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: avoid loops to create `URLSearchParams`
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
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' }
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
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.
Objects are not iterable
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.
Accepted. prefer-iterable-in-constructor